2

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>
Routfin
  • 397
  • 1
  • 11
  • 1
    Why not radio buttons ? if you're just worried about presentation/view it can be changed to with css – Code Maniac Nov 14 '22 at 04:14
  • How could I make it so that I can disable a radio button without necessarily having to select another one? in the simplest way possible – Routfin Nov 14 '22 at 04:16
  • With radio button you can always select one option only, i am not getting when you want to disable buttons ? – Code Maniac Nov 14 '22 at 04:18
  • 1
    Once I refresh the page, all my radios are unmarked, but when I mark a radio, I wish I could deselect that radio without having to mark another radio, you know? just 'no value' – Routfin Nov 14 '22 at 04:20
  • Got it, you can look at this https://stackoverflow.com/questions/2117538/how-to-uncheck-a-radio-button, hope this helps – Code Maniac Nov 14 '22 at 04:23
  • do you know any way to do this in a simpler way using state react? – Routfin Nov 14 '22 at 04:24

1 Answers1

2

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

Chris Hamilton
  • 9,252
  • 1
  • 9
  • 26