How to toggle a radio button in Typescript React?

Viewed 9091

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>
      </>
    )
  )}
}


1 Answers

Your code should be something like this: (I'm using any only because I don't know your questionnaire types, but you should consider adding the right types)

import React, { useState } from "react";

interface Props {
  questionnaire: any;
}

const Quiz = (props: Props) => {
  const [checkBox, setCheckBox] = useState();

  const handleInputChange = (score: any) => {
    setCheckBox(score);
  };

  return (
    // <-- Here you need to return something from component
    <>
     {
       props.questionnaire.questions[currentQuestion].answers.map((
      {title, score}: any) => (
        <label>
          <div>
            <input
              type="radio"
              value={score}
              name={score}
              onChange={e => handleInputChange(score)}
              checked={score === checkBox}
            />
            {title}
          </div>
        </label>
      )
    }
    </>
  );
};


Related