0

all.

I have a controlled component I am building in Storybook using React and Typescript.

As an uncontrolled component my Checkbox works fine.

I am a little stuck with my thought process and logic with it being controlled and with multiple checkboxes.

    const [isValue, setIsValue] = useState<string[]>(['']);
    const [isBoxChecked, setIsBoxChecked] = useState<boolean>(false);

    const handleOnChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        //setIsValue(e.target.value);
        setIsBoxChecked(!isBoxChecked);
        console.log(isValue, e.target.checked);
    };

    return (
        <CheckBoxGroup name="GroupTest" value={'12'} onChange={handleOnChange}>
            {/* {options.map(({ name, value, children }) => ( */}
            <>
                <CheckBox
                    value={'value'}
                    name={'name1'}
                    onChange={handleOnChange}
                    isDisabled={false}
                    isChecked={isBoxChecked}
                    id="id1"
                >
                    Child label
                </CheckBox>
                <CheckBox
                    value={'value2'}
                    name={'name2'}
                    onChange={handleOnChange}
                    isDisabled={false}
                    isChecked={isBoxChecked}
                    id="id2"
                >
                    Child label 2
                </CheckBox>
            </>

            {/* } */}
        </CheckBoxGroup>
    );
};

Now, currently when checking a checkbox the state is set for both boxes - which is obviously wrong. I am struggling on how to separate them so when I check one box only that one is checked and if I check both then both are checked.

I am also not sure how to add the value, which will be a string to the state isValue as an array of strings as I seem to have a type mismatch(Typescript....lovely).

Zack Amin
  • 514
  • 4
  • 12

1 Answers1

0

You must add another useState to control the other checkBox.

Your onChange function must change, so you can have control of both components, so when it is fired by the first CheckBox, just changes the state from the first CheckBox. About to add the value, if you specify an array of strings, you must pass it even if only one of the items is checked.

You can make an if that validates what is the target, update the isChecked state from that target. Then use the isCheckeds values to create a new Array for set in the isValue state.