J86
J86

Reputation: 15297

Can't select radio buttons when checked status has some logic

I have a couple of checkboxes that are refusing to be checked.

export default function App() {
  let model = {};

  return (
    <div className="App">
      <h1>Hello React Radio Buttons</h1>
      <p>
        Sure the model object is empty, so initially the radio will be
        unchecked, but why can't I manually check it?
      </p>
      <div>
        <input type="radio" id="opt1" checked={model.selection === "opt1"} />
        <label htmlFor="opt1">Option 1</label>
      </div>
      <div>
        <input type="radio" id="opt2" checked={model.selection === "opt2"} />
        <label htmlFor="opt2">Option 2</label>
      </div>
    </div>
  );
}

Here is a sandbox link.

The above is a simple test scenario, but I am glad I was able to replicate the problem.

The real scenario is I am trying to maintain the status of what radio button was checked when I come back to the page from an error state (i.e. form was submitted, there were errors, I want to come back to the page and maintain the selections).

Upvotes: 0

Views: 75

Answers (1)

Majid M.
Majid M.

Reputation: 4964

Because your model does't have selection key. It's better to use useStates hook same as bellow:

export default function App() {
  let model = {};
  const [checked1, setChecked1] = useState(model.selection === "opt1");
  const [checked2, setChecked2] = useState(model.selection === "opt2");
  return (
    <div className="App">
      <h1>Hello React Radio Buttons</h1>
      <p>
        Sure the model object is empty, so initially the radio will be
        unchecked, but why can't I manually check it?
      </p>
      <div>
        <input
          type="radio"
          id="opt1"
          onChange={() => setChecked1(!checked1)}
          checked={checked1}
        />
        <label htmlFor="opt1">Option 1</label>
      </div>
      <div>
        <input
          type="radio"
          id="opt2"
          onChange={() => setChecked2(!checked2)}
          checked={checked2}
        />
        <label htmlFor="opt2">Option 2</label>
      </div>
    </div>
  );
}

Upvotes: 1

Related Questions