export const QuizData = [
{
id: 0,
question: `What is the Capital of India?`,
options: [`New Delhi`, `Mumbai`, `Pune`, `Hyderabad`],
answer: `New Delhi`
},
{
id: 1,
question: `Any question here`,
options: [`any`, `options`, `here`, ` `],
answer: `ans`
},
{
id: 2,
question: `Any question here`,
options: [`any`, `options`, `here`, ` `],
answer: `ans`
},
]
//buttons
<button
className="btn btn-primary"
onClick={() => this.indexHandler(0)}
>
1
</button>
<br />
<button
className="btn btn-primary"
onClick={() => this.indexHandler(1)}
>
2
</button>
<br />
<button
className="btn btn-primary"
onClick={() => this.indexHandler(2)}
>
3
</button>
Above mentioned is the list of questions for reference. So, for now I am using static buttons,(for example as under //Buttons) and what I want is depending on the number of questions from data, the same number of buttons has to be created.
CodePudding user response:
Good approach would be maintain two separate components-
- Component which will list the questions (say
QuestionList.js
) - Question specific component to handle actions performed on that particular question. ( say
Question.js
)
QuestionList.js
const QuestionList = () => {
const QuizData = [...]
const indexHandler = (id) => {...}
return(
<>
{QuizData.map(question => (
<Question key={question.id} id={question.id} indexHandlerCallback={indexHandler} />
))}
</>)
}
Question.js
const Question = ({ id, indexHandlerCallback }) => {
const hanldeClick = () => {
// dispatch callback or any other actions
}
return (
<button className="btn btn-primary" onClick={hanldeClick}>
{id 1}
</button>
)
}