vendredi 26 novembre 2021

React material-ui multiple checkboxes and onChange not working

I have multiple checkboxes in an edit modal form, which has a record structure for update, containing the inputs including the checkboxes in state. There is one onChange event for the inputs.

When I click on a checkbox, the onChnage 'handleInputChanges' does execute. The evt.target.checked is true or false. The evt.target.name is correct and matches the name in the updateRecordStructure.

But the checkbox won't display the checked or unchecked status.

The markup:

<Grid item xs={5}>
    <FormControlLabel variant="outlined" size="small"
         control={<Checkbox
         checked={defaultChecked}
         color="primary"
         name={name}
         onChange={handleInputChanges}/>
        }
        label={label}
        id={id}
    />
</Grid>

    const updateRecordStructure ={
            id: 0,
            name: '',
            canDo1b: false,
            canDo1a: false,
            canDo2b: false,
            canDo2a: false
 };
     
 const [editRecordState, setEditRecordState] = React.useState(
    updateRecordStructure
);

   const handleInputChanges = (evt) => {
    //  Distinguish which input the change is coming from using the target.name.
    //  The square brackets around target.name, creates a dynamic key of that targets name in the object.
      
    if (evt.target.name !== '') {
        const value = evt.target.value;

         if (evt.target.checked) {
            setEditRecordState({
                ...editRecordState,
                [evt.target.name]: evt.target.checked
            });
        } else {
            setEditRecordState({
                ...editRecordState,
                [evt.target.name]: value
            });
        }
    }
};



Aucun commentaire:

Enregistrer un commentaire