Consider the following code, there are multiple checkboxes whose fields are:
<Checkbox
checked={checked[element]}
onChange={(e) => {
setChecked({ ...checked, [e.target.name]: !checked[e.target.name] });
}}
name={element}
/>
Now consider a button used to check all the checkboxes:
<Button
variant="contained"
onClick={() => {
setIsAllChecked(!isAllChecked);
Object.keys(checked).forEach((e) => {
setChecked({ ...checked, [e]: !checked[e] });
});
}}
marginRight={2}
sx={{ margin: '2rem' }}
>
{isAllChecked ? 'Unselect All' : 'Select All'}
</Button>
the onCLick logic renders through an array of all elements, and is supposed to set their value to true, but for some reason its only setting the value of the last checkbox as true. here is the checked state variable for your reference:
const [checked, setChecked] = useState({
'Add Employee Importer': false,
'Employee LOP': false,
'LOP Reversal Importer': false,
'Employee Bank Details': false,
'Employee Loan Details': false,
'Employee Category': false,
'Employee Resignation': false,
'Bulk Salary Information Of Employees': false,
'Basic Employee Information': false,
'Employee PF_ESI Details': false,
'Final Settlement Details': false,
'Add revised salary': false
});