I am doing a React Quiz based on the OpenTrivia Api, I can't figure out an way to make that only the button that you click changes it's styling, for example if there are multiple true or false questions, if I click, all the other question answers will also change the styling. That doesn't happen with any other questions, only if the answers have the exact same text, so a true or false or multiple color option for example. I've set the opacity of the radio button to zero.
This is the React code
function answerStyle(str) {
if (props.gameState == "finished") {
if (str == props.correctAnswer) {
return "correct-markedAnswer";
}
}
}
const answersElem = answerArr.map(answer => (
<div key={answer}>
<input
type="radio"
id={`${props.question} ${answer}`}
name={props.question}
value={answer}
checked={props.markedAnswers.includes(answer)}
onChange={props.onChange}/>
<label htmlFor={`${props.question} ${answer}`} className={`${answerStyle(answer)}`}>{fixText(answer)}</label>
</div>))
CSS Code
input[type="radio"] {
opacity: 0;
margin: 10px;
margin-bottom: 25px;
}
label {
border-width: 2px;
border-style: solid;
border-radius: 10px;
border-color: #2187ab;
padding: 10px;
padding-left: 30px;
padding-right: 30px;
margin-bottom: 5px;
}
input[type="radio"]:checked label {
border-width: 2px;
border-style: solid;
border-radius: 10px;
padding: 10px;
border-color: #2187ab;
background-color: #2187ab;
color: white;
padding-left: 30px;
padding-right: 30px;
}
.correct-markedAnswer {
border-width: 2px;
border-style: solid;
border-radius: 10px;
padding: 10px;
border-color: #2eb82e;
background-color: #2eb82e;
color: white;
padding-left: 30px;
padding-right: 30px;
}
CodePudding user response:
add a unique key
const answersElem = answerArr.map(answer => (
<div key={`${props.question} ${answer}`}>
<input
type="radio"
id={`${props.question} ${answer}`}
name={props.question}
value={answer}
checked={props.markedAnswers.includes(answer)}
onChange={props.onChange}/>
<label htmlFor={`${props.question} ${answer}`} className={`${answerStyle(answer)}`}>{fixText(answer)}</label>
</div>))
CodePudding user response:
The problem was with the checked value in this, removing it solved the problem.
<div key={`${props.question} ${answer}`}>
<input
type="radio"
id={`${props.question} ${answer}`}
name={props.question}
value={answer}
checked={props.markedAnswers.includes(answer)}
onChange={props.onChange}/>
<label htmlFor={`${props.question} ${answer}`} className={`${answerStyle(answer)}`}>{fixText(answer)}</label>
</div>))