Closed devYuraKim closed 1 week ago
When a button is clicked, change the color of all buttons based on whether they are the correct option.
function Options({ question }) {
const [selectedOption, setSelectedOption] = useState(null);
return (
<div className="options">
{question.options.map((option, i) => (
<button
className={`btn btn-option ${
selectedOption !== null
? i === question.correctOption
? "correct"
: "wrong"
: ""
}`}
key={i}
onClick={() => {
setSelectedOption(i);
}}
>
{option}
</button>
))}
</div>
);
}
When a button is clicked, only change the color of the button clicked, leaving the other buttons unchanged
function Options({ question }) {
const [selectedOption, setSelectedOption] = useState(null);
return (
<div className="options">
{question.options.map((option, i) => (
<button
className={`btn btn-option ${
selectedOption === i
? i === question.correctOption
? "correct"
: "wrong"
: ""
}`}
key={i}
onClick={() => {
setSelectedOption(i);
}}
>
{option}
</button>
))}
</div>
);
}
Code1 - All Buttons Change Color Based on Correct Option After Any Click
const [result, setResult] = useState("");
<button
className={`btn btn-option ${result}`}
key={i}
onClick={() =>
i === question.correctOption
? setResult("correct")
: setResult("wrong")
}
>
Code2 - All Buttons Show Correct/Wrong Status After One Click
const [selectedOption, setSelectedOption] = useState(null);
<button
className={`btn btn-option ${
selectedOption !== null
? i === question.correctOption
? "correct"
: "wrong"
: ""
}`}
key={i}
onClick={() => {
setSelectedOption(i);
}}
>
Code3 - Only the Clicked Button Shows Correct/Wrong Status
const [selectedOption, setSelectedOption] = useState(null);
<button
className={`btn btn-option ${
selectedOption === i
? i === question.correctOption
? "correct"
: "wrong"
: ""
}`}
key={i}
onClick={() => {
setSelectedOption(i);
}}
>
1. State Management:
Code 1: The result state applies universally to all buttons, so all buttons receive the same "correct" or "wrong" style, regardless of which one is clicked.
Code 2 & 3: The selectedOption state stores the index of the clicked button, allowing each button to be styled based on whether it's the correct option or not.
2. Button Styling Behavior:
3. Effect of Button Click:
reducer
function in App
componentOptions
component.answer
state management in the App
component.answer
state as a prop to the Options
component.function Options({ question, dispatch, answer }) {
const hasAnswered = answer !== null;
return (
<div className="options">
{question.options.map((option, i) => (
<button
className={`btn btn-option ${i === answer ? "answer" : ""} ${
hasAnswered
? i === question.correctOption
? "correct"
: "wrong"
: ""
}`}
key={I}
disabled={hasAnswered}
onClick={() => {
dispatch({ type: "newAnswer", payload: i });
}}
>
{option}
</button>
))}
</div>
);
}
export default Options;
I expected the
onClick
result to affect only the clicked button, but it's actually affecting the entire set of buttons.