user2371290
user2371290

Reputation: 327

unable to toggle radiobutton in react

I want to toggle a radiobutton in react. here is my logic.

const [selectedValue1, setSelectedValue1] = React.useState(false);

 const handleChange1 = event => {
if (state.selectedValue1 === false) {
      setSelectedValue1(true);

    } else {
      setSelectedValue1(false);
    }

    console.log(state.selectedValue1);
  };

Upvotes: 0

Views: 42

Answers (2)

RKM
RKM

Reputation: 144

Looks like you can use something like this

const handleChange1 = () => { setSelectedValue1(!state.selectedValue1); };

Upvotes: 0

George
George

Reputation: 36784

I think you mean to take advantage of the event object that you have available.

You could do something as simple as:

const handleChange1 = event => setSelectedValue1(event.target.checked)

Assuming of course, that your JSX looks something like the following:

<input
    type="radio"
    name="group"
    onChange={handleChange1}
    checked={selectedValue1}
/>

Upvotes: 1

Related Questions