I am trying to print checkboxes of 4 per a row, where row and values of these checkboxes comes dynamically (row count may vary )
below is my jsx code
matrix.map((row, index) => (
<TableRow key={index}>
<TableCell align="left">
{row.roleDescription}
</TableCell>
<TableCell align="right">
<FormControlLabel
control={
<Checkbox
onChange={(e) =>
setChecked({
...checked,
[e.target.name]: e.target.checked,
})
}
name={row.roleCode + `_readAccess`}
checked={(e) => checked[e.target.name]}
color="primary"
/>
}
label="Read"
/>
</TableCell>
<TableCell align="right">
<FormControlLabel
control={
<Checkbox
value={
row.writeAccess === null ? 0 : row.writeAccess
}
onChange={(e) => {}}
name="readAccess"
color="primary"
/>
}
label="Write"
/>
</TableCell>
<TableCell align="right">
<FormControlLabel
control={
<Checkbox
value={
row.checkerAccess === null
? 0
: row.checkerAccess
}
onChange={(e) =>
setMatrixForm({
...setMatrixForm,
checkerAccess: e.target.checked,
})
}
checked={
row.writeAccess &&
row.writeAccess !== "" &&
row.writeAccess === 1
? true
: false
}
name="checkerAccess"
color="primary"
/>
}
label="Checker"
/>
</TableCell>
<TableCell align="right">
<FormControlLabel
control={
<Checkbox
checked={
row.readAccess &&
row.readAccess !== "" &&
row.readAccess === 1
? true
: false
}
name="readAccess"
color="primary"
/>
}
label="Maker"
/>
</TableCell>
</TableRow>
))}
After fetching the matix data I am setting state variable const[checked, setChecked] = useState([])
as below
.then((rec) => {
if (rec.status === 200) {
let chk = [];
rec.data.data.map((item, idx) => {
var obj = {};
obj[item.roleDescription + `_readAccess`] = item.readAccess;
chk.push(obj);
obj[item.roleDescription + `_writeAccess`] = item.writeAccess;
chk.push(obj);
obj[item.roleDescription + `_checkerAccess`] = item.checkerAccess;
chk.push(obj);
obj[item.roleDescription + `_makerAccess`] = item.makerAccess;
chk.push(obj);
});
setChecked(chk);
}
})
what I have tried, is since my rows which are changing dynamically I created state variable entries with as rowName + one of check box label , so when onChange triggered on CheckBox it should change the state and check box need to be toggeled.
but Check box are not getting toggled,
EDIT ADDED SAMPLE SNIPPED in CODESANDBOX sample code
Pelse help. thx
Advertisement
Answer
Please remove === 1 ? false : true from checked because in onChange you are setting boolean
setChecked({
...checked,
[e.target.name]: e.target.checked
})
Codesandbox: https://codesandbox.io/s/wonderful-paper-lvcwe?file=/src/Demo.jsx
EDIT 1
useEffect(() => {
console.log("checked called");
}, [checked]);