javascriptreactjsradio-buttoncontrolled-component

React radio button requires two clicks to render


I'm controlling a Radio button on a react form.

The state is updating on change as expected, but the checked value isn't being rerendered on change. Therefore, from a user perspective the button isn't working.

I've replicated this in a codesandbox here https://codesandbox.io/s/eager-hertz-stzgk?file=/src/App.js

Relevant code:

const [selectedRole, setSelectedRole] = useState("staff");

...

  const handleRoleChange = (event) => {
    event.preventDefault();
    setSelectedRole(event.target.value);
  };

...

<form>
        <label>
          Staff
          <input
            type="radio"
            name="role"
            value="staff"
            checked={selectedRole === "staff"}
            onChange={handleRoleChange}
          />
        </label>
        <label>
          Student
          <input
            type="radio"
            name="role"
            value="student"
            checked={selectedRole === "student"}
            onChange={handleRoleChange}
          />
        </label>
      </form>

Appreciate any help as I'm out of ideas.

Thank you


Solution

  • That is because of event.preventDefault() in 9th line which stops it to change it instantly

    Edit 1: 2/5/2022: you can also refer to: docs