I am making react quiz app. And i want to make function that adds class active to element that is active, but in my code it adds active class to all elements in the array. I do not know how to add class only to button that is clicked. Help me please.
//...
this.state =
{
questions: [
{
title: "Question-1", answers:['a', 'b', 'c', 'd'],
correct: 2,
answered: false,
},
{
title: "Question-2", answers:['a', 'b', 'c', 'd'],
correct: 0,
answered: false,
}
],
score:0,
}
this.checkAnswer = this.checkAnswer.bind(this);
}
checkAnswer(i, j) {
const { questions, score } = this.state;
if (questions[i].correct === j && !questions[i].answered) {
questions[i].answered = true;
this.setState(
{
score: score + 1,
questions,
});
}
}
render() {
return (
<div>
{
this.state.questions.map((q, i) => (
//...
{
q.answers.map((answer, j) =>
(
<button
className={q.answered ? 'active' : ''}
key={j}
onClick={() => {
this.checkAnswer(i, j);
}}
>
{answer}
//...