Home > Blockchain >  Check a checkbox when one is checked react-hook-form
Check a checkbox when one is checked react-hook-form

Time:07-12

I have 3 checkboxes CheckboxA, CheckboxB, CheckboxC. If checkboxB or checkboxC are checked, I want checkboxA to be checked as well

basic checkbox example from react-hook-form enter image description here

CodePudding user response:

In onChange you can check if current input is not A and its value is checked so you can update your new value

if (option !== "a" && e.target.checked) valueCopy[0] = "a";

Checkboxes

const Checkboxes = ({ options, control, name }) => {
  const { field } = useController({
    control,
    name
  });

  return (
    <>
      {options.map((option, index) => (
        <input
          onChange={(e) => {
            const valueCopy = [...field.value];

            valueCopy[index] = e.target.checked ? e.target.value : null;
            if (option !== "a" && e.target.checked) valueCopy[0] = "a";
            field.onChange(valueCopy);
          }}
          key={option}
          type="checkbox"
          checked={field.value.includes(option)}
          value={option}
        />
      ))}
    </>
  );
};

You can check in my codesandbox

CodePudding user response:

Try adding this on your line 27:

(valueCopy[1] === 'b' || valueCopy[2] === 'c') && (valueCopy.shift(), valueCopy.unshift('a'));
  • Related