I have a function in React in which I'm trying to change the state and add a class that styles the clicked button. The problem is that when I avoid altering the state in the userAnswers() function the style does work, but when I add setChoices() the style doesn't work. This is the code:
function userAnswers (e) {
const choiceBtns = document.querySelectorAll(".choice-btns")
choiceBtns.forEach((btn) => {
if (e.target.id === btn.id) {
btn.classList.remove("chosen")
}
})
e.target.classList.add("chosen")
setChoices((prev) => {
return prev.map((q) => {
return {...q, [e.target.value]: false}
})
})
setChoices((prev) => {
return prev.map((q) => {
if (q.id === e.target.id) {
return {...q, [e.target.value]: true}
} else {
return {...q}
}
})
})
}
I don't know I'm missing something here! Any help would be appreciated.