mercredi 12 août 2020

Append and remove the value of checkbox into an array state in reactjs

I am using mui checkbox component and this is how I'm displaying it:

 <FormControl component="fieldset">
    <FormGroup aria-label="position" column>
        {sortedData.map((obj) => {
            return (
                <FormControlLabel
                    value="type"
                    control={<Checkbox color="primary"/>}
                    label={obj}
                    name={obj}
                    onChange={handleTypeCheckboxChange}
                    labelPlacement="end"
                />
            );
        })}
    </FormGroup>
</FormControl>

Now on this function handleTypeCheckboxChange I want to add or remove the values of the checkboxes wehn the user checks or unchecks.

This is how I tried to do but it isn't working. It gives me NaN :

const [typeValue, setTypeValue] = useState([]) // the state array where i wanna store the checkbox checked values

const handleTypeCheckboxChange = (event) => {

    let typeValuesArray = []
    let index

    if (event.target.checked) {
        setTypeCheckboxCount(prevState => prevState + 1)
        typeValuesArray.push(+(event.target.name))
    } else {
        setTypeCheckboxCount(prevState => prevState - 1)
        index = typeValuesArray.indexOf(+(event.target.name))
        typeValuesArray.splice(index, 1)
    }

    setTypeValue(typeValuesArray)
}

Can anyone help me with this? Thanks!




Aucun commentaire:

Enregistrer un commentaire