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 }
questionsAnswersthe other overoptions. Do not use.forEach. I recommendmaporfor … of.state, ever. The wordstateimplies that it changes, precisely what quiz questions and answers never do. Also, theanswerfield should contain the index of the options array that stores the correct answer.optionsas prop, then use a second loop inside the Component'srender()to render the options.