I need to set the default value to my react material UI check box. So I did this task using React.useEfect hook.
This is how it looks like after setting the value using useEfect.
But now I am facing a problem. After I unchecked my check box, I can’t check again. And I have no idea what going on with my code. If anyone can help me with this, I am really thankful for that.
const [checked, setChecked] = React.useState({});
const variant= useSelector((state) => state.promoCodesReducer.selectedPromo);
React.useEffect(()=>{
variant && variant.filter((filterData)=>
setChecked((newValues) => ({ ...newValues, [filterData.variantId]:checked })))
},[row,variant])
My Check Box Component :
function addVariantSection(data) {
return (
<Grid key={data._id} container spacing={1}>
<Grid item xs={12} style={{ justifyContent: 'space-between', display: 'flex', flexDirection: 'row' }}>
<div style={{ margin: 10 }}>{`${data.productName ? data.productName : itemName}-${data.variant1} ${data.variant2}`}</div>
<div>
<Checkbox
// eslint-disable-next-line no-useless-concat
id={`${data.variantId ? data.variantId:data._id}-` + `checkData`}
color='primary'
// checked={checked[data._id ? data._id:data.variantId]}
checked={checked[data.variantId ? data.variantId:data._id]}
onChange={handleChecked(data.variantId ? data.variantId:data._id,data.productId)}
style={{ margin: 10 }}
/>
</div>
</Grid>
</Grid>
);
}
Methord for check box Value :
const handleChecked = (id,pid) => (e) => {
const { checkedID } = e.target;
const vID = e.currentTarget.id.split('-', 1);
setChecked((values) => ({ ...values, [id]: checkedID }));
};