'React quiz select answers list with css
In my quiz app, one questions have two answers.Currently when clicking answers it doesn't change color and cann't be selected. When answer is clicked it should change color and can be selected from list like radio button. when both options are selected(colored) we should submit.
{questions[currentQuestion].answerOptions.map((answerOption) => (
<button
className="button"
onClick={() => handleAnswerOptionClick(answerOption.isCorrect)}
>
{answerOption.answerText}
</button>
))}
Solution 1:[1]
There is a lot of refactoring you need to do here:
- Merge all the functions of handleAnswerOptionClick, handleAnswerOptionClick1, handleAnswerOptionClick2 etc.. to one function with key index and value.
- Merge all the answerOptions into one data structure.
Use rule of thumb- if you write the exact code more the 3 times, you should consider using it with iterator like "for"
But to answer your question about changing the css of the right answer :
<button
className={"button " + (answerOption.isCorrect ? 'correctClass' : '')}
onClick={() => handleAnswerOptionClick(answerOption.isCorrect)}
>
Css section-
.correctClass{
background-color: lightblue;
}
I added a condition in the class name which apply new class when the answer is correct.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
