React JS :: Difficulty Applying Conditional Rendering to Multiple Array Items

I am trying to set up a quiz questions page (using an API) where, if you select the correct answer for the specific question, the text will show green and the score will increment by one and, if the incorrect answer is selected, the text will show red and the score will remain unchanged.

I am able to apply the logic if there is only one question but, when trying to apply it to ten questions, it applies the changes to each question.

Please see the console and application screenshots below:

  • For one question:

Screenshot - One question

  • For ten questions:

Screenshot - Ten Questions

My code is as follows:

import React, { useState } from "react";
import { useLocation } from "react-router-dom";
import "../App.css";
import { Row, Col, Card, Button } from "react-bootstrap";

const Questionnaire = () => {
  const [selectedAnswer, setSelectedAnswer] = useState("");
  const [style, setStyle] = useState("");
  const [score, setScore] = useState(0);

  const location = useLocation();
  const quiz = location.state.quiz;

  // Added:_______________________________//
  const answerOptions = {
    a: "answer_a",
    b: "answer_b",
    c: "answer_c",
    d: "answer_d",
    e: "answer_e",
    f: "answer_f",
  };

  const answerOptionsArray = Array.from(
    { length: quiz.length },
    () => answerOptions
  );

  const questionIndex = Array.from({ length: quiz.length }, (_, i) => i + 1);

  const masterData = questionIndex.map((index, i) => {
    return {
      questionIndex: index,
      answerOptions: answerOptionsArray[i],
      quiz: quiz[i],
    };
  });

  const setAnswer = (e) => {
    const optionValues = answerOptionsArray.map((option) => Object.values(option.a))
    const optionExists = Object.values(answerOptionsArray).includes("answer_a");

    if (optionExists == true) {
      setSelectedAnswer(e.target.value);
    }
    console.log(optionValues);
    // Returns: [ 'answer_a', 'answer_b', 'answer_c', 'answer_d', 'answer_e', 'answer_f' ]
    console.log(e.target.value);
    // Returns: answer_a (If button with "answer_a" is clicked on).
    console.log(optionExists);
    // Returns: false
    console.log(selectedAnswer);
    // Returns: Empty log
  };
  //______________________________________//

  const checkAnswers = (e) => {
    const correctAnswers = masterData.map(
      (answer) => answer.quiz.correct_answers
    );

    const answerCheckA = correctAnswers.map(
      (answer) => answer.answer_a_correct
    );
    const answerCheckB = correctAnswers.map(
      (answer) => answer.answer_b_correct
    );
    const answerCheckC = correctAnswers.map(
      (answer) => answer.answer_c_correct
    );
    const answerCheckD = correctAnswers.map(
      (answer) => answer.answer_d_correct
    );
    const answerCheckE = correctAnswers.map(
      (answer) => answer.answer_e_correct
    );
    const answerCheckF = correctAnswers.map(
      (answer) => answer.answer_f_correct
    );

    if (answerCheckA == "true" && selectedAnswer == "answer_a") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else if (answerCheckB == "true" && selectedAnswer == "answer_b") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else if (answerCheckC == "true" && selectedAnswer == "answer_c") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else if (answerCheckD == "true" && selectedAnswer == "answer_d") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else if (answerCheckE == "true" && selectedAnswer == "answer_e") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else if (answerCheckF == "true" && selectedAnswer == "answer_f") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else {
      setStyle("incorrect-answer");
      setScore(score);
    }
    console.log("Score: " + score);
  };

  // Adjusted buttons to accommodate for the above changes and moved "checkAnswers()" button to the bottom.

  return (
    <div>
      <Row>
        <Col>
          <h3 className="quiz-component-header">
            Quiz: {quiz[0].category} &#10088; {quiz[0].difficulty} &#10089;
          </h3>
        </Col>
      </Row>
      {Object.values(masterData).length !== 0 ? (
        <div>
          <Row>
            <Col>
              {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>
                  {content.quiz.answers.answer_a !== null ? (
                    <Button
                      value="answer_a"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_a" ? style : undefined
                      }
                    >
                      a. {content.quiz.answers.answer_a}
                    </Button>
                  ) : (
                    <div></div>
                  )}
                  {content.quiz.answers.answer_b !== null ? (
                    <Button
                      value="answer_b"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_b" ? style : undefined
                      }
                    >
                      b. {content.quiz.answers.answer_b}
                    </Button>
                  ) : (
                    <div></div>
                  )}
                  {content.quiz.answers.answer_c !== null ? (
                    <Button
                      value="answer_c"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_c" ? style : undefined
                      }
                    >
                      c. {content.quiz.answers.answer_c}
                    </Button>
                  ) : (
                    <div></div>
                  )}
                  {content.quiz.answers.answer_d !== null ? (
                    <Button
                      value="answer_d"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_d" ? style : undefined
                      }
                    >
                      d. {content.quiz.answers.answer_d}
                    </Button>
                  ) : (
                    <div></div>
                  )}
                  {content.quiz.answers.answer_e !== null ? (
                    <Button
                      value="answer_e"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_e" ? style : undefined
                      }
                    >
                      e. {content.quiz.answers.answer_e}
                    </Button>
                  ) : (
                    <div></div>
                  )}
                  {content.quiz.answers.answer_f !== null ? (
                    <Button
                      value="answer_f"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_f" ? style : undefined
                      }
                    >
                      f. {content.quiz.answers.answer_f}
                    </Button>
                  ) : (
                    <div></div>
                  )}
                </Card>
              ))}
            </Col>
          </Row>
          <Button type="submit" onClick={checkAnswers}>
            Check Score
          </Button>
          <h3>Score: {score} / 10</h3>
        </div>
      ) : (
        <div>
          <h3>There are Currently No Questions For Your Query</h3>
          <h4>Watch This Space For Added Questions</h4>
        </div>
      )}
    </div>
  );
};

export default Questionnaire;

Please may someone assist? I would appreciate any help that anyone is willing to offer.



from Recent Questions - Stack Overflow https://ift.tt/7H945bZ
https://ift.tt/Jsx1hei

Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)