React radio button requires two clicks to render Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of React radio button requires two clicks to render without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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

Answer

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

We are here to answer your question about React radio button requires two clicks to render - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji