I have a data file with an array of objects and each object consists of “Question” and “Multi choice answers” . What I’m doing is mapping over the array and displaying the list of questions, which works just fine. and I want the background of the option to change when I click on it but it is changing [EVERY element] ,in the list instead of just that one item that was clicked on. and i also wanted it to change to green if the answer is correct and to red of the answer is wrong.
below is the Array of data
xport const QuestionsList = [
{
image: BrazilFlag,
options: [
{ Answertext: "Brazil", IsitCorrect: true },
{ Answertext: "Germany", IsitCorrect: false },
{ Answertext: "Oman", IsitCorrect: false },
{ Answertext: "Russia", IsitCorrect: false },
],
},
{
image: IndiaFlag,
options: [
{ Answertext: "USA", IsitCorrect: false },
{ Answertext: "Saudi Arabia", IsitCorrect: false },
{ Answertext: "India", IsitCorrect: true },
{ Answertext: "Sirilanka", IsitCorrect: false },
],
},
and below is my React Component
export const Question1 = () => {
const [currentQuestion, setCurrentQuestion] = useState(0);
const [showScore, setShowScore] = useState(true);
const [score, setScore] = useState(0);
const AnsweredQuestion = (IsitCorrect) => {
const nextQuestion = currentQuestion + 1;
if (IsitCorrect) {
setScore(score + 1);
}
if (nextQuestion < QuestionsList.length) {
setCurrentQuestion(nextQuestion);
} else {
setShowScore(true);
}
};
return (
<motion.div
className="question-box"
variants={Question1Variant}
initial="hidden"
animate="visible"
exit="exit"
>
<div className="show-score">
{showScore ? (
<div className="score-section">
{`You scored ${score} out of ${QuestionsList.length}`}
</div>
) : (
<>// ... quiz question/answer markup</>
)}
</div>
<motion.div className="question-flag">
<img src={QuestionsList[currentQuestion].image} alt="photo" />
</motion.div>
<div className="question-heading">
<h1>Pick The Right Country's Flag</h1>
</div>
<div className="question-option">
{QuestionsList[currentQuestion].options.map((option, index) => {
return (
<button
key={index}
className="question-option-paragraph "
onClick={() => AnsweredQuestion(option.IsitCorrect)}
>
{option.Answertext}
</button>
);
})}
</div>
your feedback is pretty much appreciated.