0

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}
                     //...

1 Answers1

0

With this code, if a question is answered it will add the active className to your all answer buttons. I think you need to keep a selected property in answers array.

questions: [
    {
        title: "Question-1", 
        answers: [
                {
                    text: "a",
                    selected: true
                },
                {
                    text: "b",
                    selected: false
                },
                {
                    text: "c",
                    selected: false
                },
                {
                    text: "d",
                    selected: false
                }
        ],
        correct: 2,
        answered: false,
    }
]

And to make the selected answer's className active, your code must be:

q.answers.map((answer, j) =>
    (
        <button
            className={a.selected ? 'active' : ''}
            key={j}
            onClick={() => {
                this.checkAnswer(i, j);
            }}
        >
            {answer}
    ...

SuleymanSah
  • 13,055
  • 5
  • 17
  • 42