Routfin
Routfin

Reputation: 457

How to select only one checkbox instead of being able to select more than one? (react)

I would like to only be able to select a single checkbox and not all or more than one. I would like to use checkbox instead of radio because I can disable it without having to mark another radio

     <C.SingleCard>
            <h2>Pizza</h2>
            <div>
                <hr />
                <h3>Flavors</h3>
                <hr />
            </div>
            <div>
                <h4>Pepperoni</h4>
                <input type="checkbox" name='flavor' />
            </div>
            <div>
                <h4>Chicken</h4>
                <input type="checkbox"  name='flavor' />
            </div>
            <div>
                <h4>Bacon</h4>
                <input type="checkbox"  name='flavor'  />
            </div>
            <div>
                <button>Add</button>
            </div>
        </C.SingleCard>

Upvotes: 3

Views: 4661

Answers (1)

Chris Hamilton
Chris Hamilton

Reputation: 10954

Here's the simplest way I can think of:

Put the options in an array and just keep track of the selected index. Set the index to null if the user selected the same index. Use the index parameter of map to set checked=true on the selected box. The onChange callback will trigger when the user selects one of the boxes, you can ignore the event parameter and just pass the index of the box.

const options = ['pepperoni', 'chicken', 'bacon'];

export default function App() {
  const [selected, setSelected] = useState(null);

  function onChange(i) {
    setSelected((prev) => (i === prev ? null : i));
  }

  function whatDidIPick() {
    console.log(options[selected] || 'nothing');
  }

  return (
    <div>
      {options.map((o, i) => (
        <label key={i}>
          {o}
          <input
            type="checkbox"
            checked={i === selected}
            onChange={() => onChange(i)}
          />
        </label>
      ))}
      <br />
      <button onClick={whatDidIPick}>Log what I picked</button>
    </div>
  );
}

https://stackblitz.com/edit/react-ts-1uwfcq?file=App.tsx

Upvotes: 2

Related Questions