Darkbound
Darkbound

Reputation: 3434

How to create a RadioButtonGroup with "pure" react?

I am trying to create a radio group that can be handled with the onChange function provided to the parent div:

  const handleAgeGroupOnChange = (e) => {
    console.log(e.target.value)
  };

  <div onChange={handleAgeGroupOnChange} className="flex flex-col">
    <label>
      <input type="radio" value="18-34" name="18-34" />
      18-34
    </label>
    <label>
      <input type="radio" value="35-49" name="35-49" />
      35-49
    </label>
    <label>
      <input type="radio" value="50+" name="50+" />
      50+
    </label>
    <label>
      <input type="radio" value="all" name="Mix all ages" />
      Mix all ages
    </label>
  </div>

The logging is working, I am getting all of the correct values, however the checked state of the buttons is not updated correctly, if I click all of the buttons, all of them will stay checked.

Do I have to do the checked property for each button, and is there a way to do this, without having to manually do checked on each radio button?

Upvotes: 0

Views: 242

Answers (1)

Win
Win

Reputation: 5584

To make things easier, I would put the options into an array and just map them like the below and give each radio button the same name and just make them readOnly.

const options = ["18-34", "35-49", "50+", "Mix all ages"];

function App() {
  const [age, setAge] = React.useState("");

  const handleOnChange = (evt) => {
    const { value } = evt.target;
    setAge(value);
  };

  return (
    <div className="App">
      {options.map((option) => (
        <div key={option}>
          <label>
            <input
              type="radio"
              name="age"
              value={option}
              readOnly={true}
              checked={age === option}
              onChange={handleOnChange}
            />
            {option}
          </label>
        </div>
      ))}
      <pre>Selected option: {age}</pre>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Upvotes: 1

Related Questions