score:0

const Questionnaire = () => {
  .
  .
  const [selectedAnswer, setSelectedAnswer] = useState({});
  .
  .
  const [style, setStyle] = useState({});
  .
  .
  const setAnswerForQuestion = (qIdx, answerKey) => {
    setSelectedAnswer(prev => ({...prev, [qIdx]: answerKey}));
  };
  .
  .
  const checkAnswers = () => {
    const correctAnswers = quiz[0].correct_answers; // quiz[0] only
    // see <h3 className="quiz-component-header">
    // only quiz[0] is rendered in this component
    const tempScore = correctAnswers.reduce((total, ans, qIdx) => (
      total + ( ans === selectedAnswers[qIdx] ? 1 || 0)
    ), 0);
    setScore(tempScore);
    // Now, set style for each question's answer
    setStyle(correctAnswers.reduce((fin, ans, qIdx) => ({
      ...fin,
      [qIdx]: 
        ans === selectedAnswers[qIdx]
          ? 'correct-answer'
          : 'incorrect-answer'
    }), {}));
  };
  .
  .
  .
  return (
    .
    .
    {masterData.map((content, i) => (
      <Card key={i} className="col-md-11 question-card" content={content}>
        <Card.Title>QUESTION {content.questionIndex}</Card.Title>
        <Card.Body>
          <Card.Text>{content.quiz.question}</Card.Text>
        </Card.Body>
        <Card.Title>SELECT YOUR ANSWER</Card.Title>
        { Object.entries(content.quiz.answers).map(([k, v], aIdx) => (
            v !== null &&
            <Button
              value={k}
              className={style[i] || undefined}
              onClick={() => setAnswerForQuestion(i, k)}
            >
              {String.fromCharCode(97 + aIdx)}. {v}
            </Button>
          ))
        }
        
        .
        .
        .
      </Card>
      .
      .
      .
      <Button type="submit" onClick={checkAnswers}>
        Check Score
      </Button>
      <h3>Score: {score} / 10</h3>
      .
      .
    )}
    .
    .
  );
}

Related Query

More Query from same tag