Abed Aarabi
Abed Aarabi

Reputation: 149

checkBox once at the time in React

I am trying to select one checkbox at a time in order to setState with a specific value, the problem is that I am not sure if I need to loop over all the checkboxes and un-select the one that I didn't click.

in my case here I am using the value value="Fanny" | value="Abed" in order to identify which checkbox i cliciked

  const [check, setcheck] = React.useState(false);
  const [checkBoxValue, setCheckBoxValue] = React.useState(null);
  const [info, setInfo] = React.useState(null);
 
 
  React.useEffect(() => {
    if (check && checkBoxValue === "Abed") {
      setInfo("Abed");
    } else if (check && checkBoxValue === "Fanny") {
      setInfo("Fanny");
    } else {
      setInfo(null);
    }
  }, [check, checkBoxValue]);



return (   <label>
              <input
                value="Abed"
                type="checkbox"
                defaultChecked={check}
                onChange={(e) => {
                  setcheck(!check);
                  setCheckBoxValue(e.target.attributes.value.value);
                }}
              />
              Abed!
            </label>
            <label>
              <input
                value="Fanny"
                type="checkbox"
                defaultChecked={check}
                onChange={(e) => {
                  setcheck(!check);
                  setCheckBoxValue(e.target.attributes.value.value);
                }}
              />
              Fanny!
            </label>
          </div>
        </>
      )}
    </div>
  );

Upvotes: 1

Views: 723

Answers (1)

Yoshi
Yoshi

Reputation: 54649

You're making this a lot more complicated than it needs to be. If only one checkbox should be checked, then ultimately that means you only have one value. Meaning you only need to keep track of that value. E.g.:

import { useState } from 'react';

export const Foo = () => {
  const [checked, setChecked] = useState(null);
  const toggle = evt => setChecked(current => current === evt.target.value ? null : evt.target.value);

  return (
    <>
      <label>
        <input
          value="Abed"
          type="checkbox"
          checked={checked === 'Abed'}
          onChange={toggle}
        />
        Abed!
      </label>

      <label>
        <input
          value="Fanny"
          type="checkbox"
          checked={checked === 'Fanny'}
          onChange={toggle}
        />
        Fanny!
      </label>
    </>
  );
};

Upvotes: 1

Related Questions