I am making a quiz project in ReactJS using Trivia API. If I click one option from 4 options, then it should be selected and simultaneously deselect all other options. Moreover, if I click it again, then it should be deselected. I am a complete beginner in React. Please help me!!!
function Questionnaire(props){
return(
<div className="question">
<div className="ques">{props.ques}</div>
<ul className="options">
<li>{props.incorrAns[0]}</li>
<li>{props.corrAns}</li>
<li>{props.incorrAns[1]}</li>
<li>{props.incorrAns[2]}</li>
</ul>
</div>
)
}
CodePudding user response:
You can use states of the react
function Questionnaire(props){
const [selectedOption, setSelectedOption] = useState("")
const setOptions = (opt) => {
setSelectedOption(opt);
}
return(
<div className="question">
<div className="ques">{props.ques}</div>
<ul className="options">
<li onClick={() => setOptions(props.incorrAns[0])}>{props.incorrAns[0]}</li>
<li onClick={() => setOptions(props.corrAns)}>{props.corrAns}</li>
<li onClick={() => setOptions(props.incorrAns[1])}>{props.incorrAns[1]}</li>
<li onClick={() => setOptions(props.incorrAns[2])}>{props.incorrAns[2]}</li>
</ul>
</div>
)
}
CodePudding user response:
To start, for this kind of assignment I would probably use <input type="radio">
which you can read about here.
But here's a possible solution for you using your code
import { useState } from "react";
function Questionnaire(props) {
const {
corrAns,
incorrAns,
ques
} = props;
const [selectedAnswer, setSelectedAnswer] = useState("");
const handleClick = (answer) => {
if (answer !== selectedAnswer) {
setSelectedAnswer(answer);
} else {
setSelectedAnswer("");
}
};
return (
<div className="question">
<div className="ques">{ques}</div>
<ul className="options">
{[...incorrAns, corrAns].map((answer) => (
<li
key={answer.id}
style={answer === selectedAnswer ? { color: "blue" } : null}
onClick={() => handleClick(answer)}
>
{answer}
</li>
))}
</ul>
</div>
);
}
export default Questionnaire;
Some explanation of what we're doing here, first we destructure props
so it will be nicer to use. We set a state called selectedAnswer
that will hold the current selected answer.
I took the liberty to use the map()
function in order to reduce the number of times you write the <li>
element by concatenating corrAns
and incorrAns
to one array.
We then set an onClick
function so when you click an answer it triggers the handleClick
function which checks if you selected a different answer or not, if it's a different answer we highlight the new answer chosen. If the chosen answer is the same as before we just remove the highlight from the answer as requested.