I know this is a rookie question, but I'm stuck and I can't seem to find what I'm looking for.
I have a Typescript file (.tsx) and four answer choices. The user can only pick one. However, when the user clicks more than one radio button, you guessed it, the previously selected buttons stay selected.
I've seen examples where others use:
<input type="radio"
value="option1"
checked={this.state.selectedOption === 'option1'}
onChange={this.handleOptionChange} />
This may work for some, but in my .tsx file, I can't use this.state. Every reference I find is using this scenario.
I tried using this in my handleInputChange function, but all the radio buttons became selected.
e.target.value === e.target.name ? setChecked(true) : setChecked(false)
Here's what I have and thanks in advance for any advice.
// Quiz.tsx
import React, { useState } from "react"
interface Props {
questionnaire: any
}
const Quiz = (props: Props) => {
// setting checked state to false by default
const [checked, setChecked] = useState(false)
const handleInputChange = (e: any) => {
// if the current value equals the current input name, mark checked as true
// However this makes all radio buttons checked as true (all selected)
e.target.value === e.target.name ? setChecked(true) : setChecked(false)
}
{props.questionnaire.questions[currentQuestion].answers.map(
({ title, score }: any) => (
<>
<label>
<div>
<input
type="radio"
value={score}
name={score}
onChange={e => handleInputChange(e)}
checked={checked}
/>
{title}
</div>
</label>
</>
)
)}
}