I am mapping over the request variable and rendering it on the page, it has an array of object with a question, correct_answer and incorrect_answer properties, and I also set a state named disable that is toggled between true and false when the correct_answer button is clicked to make the correct answer button get disabled or unclickable for each question, but clicking the correct answer button for ONE question disables all correct answer buttons for the OTHER questions
I basically want to disable the correct answer button on click or making it clickable once
const [request, setRequest] = React.useState([])
const [disable, setDisable] = React.useState(false);
function scoreFunction (event){
setDisable(true)
setScore(prevScore => prevScore + 1)
}
React.useEffect (() => {
fetch('https://opentdb.com/api.php?amount=5')
.then(res => res.json())
.then(data => setRequest(data.results.map(({ question, correct_answer, incorrect_answers }) => ({question, correct_answer, incorrect_answers}))))
}, [])
// console.log(request)
const questionElements = request.map(req => {
return (
<Question
question = {req.question}
correct_answer ={req.correct_answer}
incorrect_answers = {req.incorrect_answers}
scoreFunction = {scoreFunction}
disabled = {disable}
/>
)
})
// The Question Component
export default function Question (props){
const incorrectAnswers = props.incorrect_answers.map(ans => {
return (
<button className ="button">{ans}</button>
)
})
return(
<div className = "question-div">
<h1 className = "question">{props.question}</h1>
<div className = "answerBlock">
<button
disabled = {props.disabled}
className ="button correct"
onClick = {props.scoreFunction}>{props.correct_answer} </button>
{incorrectAnswers}
</div>
<hr />
</div>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
Essentially the issue is because your disabled useState is in the wrong place. It needs to be inside the Question component so you have 1 disabled flag per question rather than 1 global one.
export default function Question (props) {
const [disabled, setDisabled] = useState(false)
const incorrectAnswers = props.incorrect_answers.map(ans => {
return (
<button className ="button">{ans}</button>
)
})
return(
<div className = "question-div">
<h1 className = "question">{props.question}</h1>
<div className = "answerBlock">
<button
disabled = {disabled}
className ="button correct"
onClick = {() => {
setDisabled(true)
props.scoreFunction()
}>{props.correct_answer} </button>
{incorrectAnswers}
</div>
<hr />
</div>
)
}