1

I want to select only one option in the group of radio buttons. i can only find class component code online. Also help me with a onChange function to handle this.

const [radioOption, setradioOption]= useState(true)

const handleRadioChange = () =>{

}
    return(
<>
<Form.Group 
    inline 
    style={{
        display:'flex',  
        justifyContent:'space-between'}}
    >
    <Form.Radio
    onChange={handleRadioChange}
    value="All devices"
    label='All devices' 
    defaultChecked/>

    <Form.Radio
    onChange={handleRadioChange}
    value='Mobile only'
    label='Mobile only'/>

    <Form.Radio
    onChange={handleRadioChange}
    value='Desktop only'
    label='Desktop only'/>

</Form.Group>


</>)

1 Answer 1

17

To select only one option in the group of radio buttons you need to use same name in every input of radio. To save your choice we can use useState. Here is the complete example:

import React, { useState } from "react";

function Demo() {
  const [gender, setGender] = useState("Male");

  function onChangeValue(event) {
    setGender(event.target.value);
    console.log(event.target.value);
  }

  return (
    <div onChange={onChangeValue}>
      <input type="radio" value="Male" name="gender" checked={gender === "Male"} /> Male
      <input type="radio" value="Female" name="gender" checked={gender === "Female"}/> Female
      <input type="radio" value="Other" name="gender" checked={gender === "Other"} /> Other
    </div>
  );
}

export default Demo;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.