I have a MUI checkbox:
<Checkbox
checked={rowValues[row.id]}
onChange={() => {
const temp = { ...rowValues, [row.id]: !rowValues[row.id] };
setRowValues(temp);
}}
inputProps={{ 'aria-label': 'controlled' }}
/>
and there is a select all button
<Button
onClick={async () => {
isAllSelected = !isAllSelected;
const tmp = await setAllValues(isAllSelected);
setRowValues(tmp);
}}
size="small"
variant="contained"
>
{isAllSelected ? 'Unselect All' : 'Select All'}
</Button>
Both of these make use of the rowValues whoose structure looks like this:
{
625fd0bc4163c339b4235286: true
627df6084067debf4de42287: true
629a481d848843b1baaf7945: true
6260feb706684d04a43da863: true
62809135dbf57c3ee8d7efd4: true
}
Code related to default value and initialization:
const [rowValues, setRowValues] = useState([]);
let temp = [];
async function setAllValues(value) {
await stableSort(rows, getComparator(order, orderBy))
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.forEach((row) => {
temp = { ...temp, [row.id]: value };
});
console.log('| temp', temp);
return temp;
}
React.useEffect(() => {
setAllValues(false).then(setRowValues);
}, []);
When i click the select all button, all the values for the corresponding ID's get changed to true. Now for the checked prop in the checkbox, Im setting it to the value for the corresponding ID(either true or false). Instead i got an error:
index.js:1 Material-UI: A component is changing the uncontrolled checked state of SwitchBase to be controlled.
Elements should not switch from uncontrolled to controlled (or vice versa).
Decide between using a controlled or uncontrolled SwitchBase element for the lifetime of the component.
The nature of the state is determined during the first render. It's considered controlled if the value is not undefined.
That happens because your initial value is undefined/null. Use '' instead, that should solve the problem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With