0

In my ReactJs I set the following state:

this.state = {
questionsAnswer: [
        { // first question
          question: 'A simple question: ',
          options: [ 'Answer1', 'Answer2', 'Answer3'],
          answer: 'Answer3',
        },
        { // second question
          question: 'Second Simple Question',
          options: ['Answer1', 'Answer2'],
          answer: 'Answer1'
        }]}

It's a quiz-like application which checks your answers. The problem I have is that I render an element based on the length of 'options'. Let that element be a div for the simplicity. When I render question 1, three divs are rendered; when in question 2, two divs are rendered.

The problem I have is that I can't dynamically access inside elements of the object state so I can render the number of DIVs. For example, we can do this.state.questionsAnswer[0].options.length to access the length of the first element and change index to get second element.

What is the best approach to render elements based on the length of options?

What I tried was that:

for (let i = 0; i < this.state
                              .questionsAnswer[0]
                              .options
                              .length; i++) { //// render div here }

Should I run another loop inside the questionsAnswer? Or Maybe a beforeEach?

Another thing I must mention is that I'm trying to access it after render(){//here }

3
  • 2
    Sounds like you want nested loops, one over questionsAnswers the other over options. Do not use .forEach. I recommend map or for … of. Commented Nov 7, 2018 at 22:15
  • 1
    Let me just say that you shouldn't put hardcoded data in state, ever. The word state implies that it changes, precisely what quiz questions and answers never do. Also, the answer field should contain the index of the options array that stores the correct answer. Commented Nov 7, 2018 at 22:15
  • 1
    Nested loops are one way, the other is to create a Question Component and pass options as prop, then use a second loop inside the Component's render() to render the options. Commented Nov 7, 2018 at 22:17

1 Answer 1

1

The problem I have is that I can't dynamically access inside elements of the object state so I can render the number of DIVs.

Yes you can! You can map through the questions and the map through the options, returning the div.

this.state.questionsAnswer.map(question => {
  return question.options.map(option => {
    <div>stuff</div>
  })
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.