mercredi 21 avril 2021

Get value of Checkbox in react custom checkbox

I have this dynamic checkbox, that I want to update the state with the selected options only ,I tried to add some checks to filter the state on change , but it seems I am not seeing what went wrong!

const checkBoxesOptions = [
    { id: 1, title: 'serviceOne' },
    { id: 2, title: 'serviceTwo' },
    { id: 3, title: 'serviceThree' },
];

const [selectedCheckBoxes, setSelectedCheckBoxes] = React.useState([]);

{checkBoxesOptions.map((checkBox, i) => (
                    <CheckBox
                        key={i}
                        label={checkBox.title}
                        value={1}
                        checked={false}
                        onChange={value => {
                            let p = {
                                title: checkBox.title,
                                isTrue: value,
                            };
                            if (p.isTrue) {
                                const tempstate = selectedCheckBoxes.filter(
                                    checkbox => checkbox !== checkBox.title
                                );
                                console.log('temp state', tempstate);
                                setSelectedCheckBoxes([...selectedCheckBoxes, p.title]);
                            }

        
                            console.log(p);
                        }}
                    />
                ))}



Aucun commentaire:

Enregistrer un commentaire