Currently, on my quiz page, all answer options are colorized when clicked. However, only the single answer option should be recolored according to its correctness. The data is pulled from a data.json array.
export default function QuizCard({ title, scenario, question, answers }) {
const [bgColor, setBgColor] = useState('gray')
function handleAnswerClick(isCorrect) {
if (isCorrect === true) {
setBgColor('green')
} else {
setBgColor('red')
}
}
return (
<>
<Card bgColor={bgColor}>
<h2>{title}</h2>
<p>{scenario}</p>
<h3>{question}</h3>
<AnswerSection>
{answers.map((answer => (
<AnswerButton
key={index}
onClick={() => handleAnswerClick(answer.isCorrect)}
isCorrect={answer.isCorrect}
bgColor={bgColor}
>
{answer.answerText}
</AnswerButton>
))}
</AnswerSection>
</Card>
What do I need to do to highlight only the selected answer in red or green depending on its correctness without recoloring all other options as well?
Thank you very much for your help and apologies for the vague question. I started coding 2 months ago and I am not yet so familiar with the terminology.
You can do this that:
export default function QuizCard({ title, scenario, question, answers }) {
const [bgColor, setBgColor] = useState('gray')
const [selectAnswer, setSelectAnswer] = useState(null)
const handleAnswerClick = (isCorrect, answer) => {
if (isCorrect === true) {
setBgColor('green')
} else {
setBgColor('red')
}
setSelectAnswer(answer)
}
return (
<>
<Card bgColor={bgColor}>
<h2>{title}</h2>
<p>{scenario}</p>
<h3>{question}</h3>
<AnswerSection>
{answers.map(answer => (
<AnswerButton
key={answer.answerText}
onClick={() =>
handleAnswerClick(answer.isCorrect, answer.answerText)
}
isCorrect={answer.isCorrect}
bgColor={answer.answerText === selectAnswer ? bgColor : 'gray'} // assign bgColor in state only to the right answer and for others use gray as default
>
{answer.answerText}
</AnswerButton>
))}
</AnswerSection>
</Card>
</>
)
}