I am working with backend value whos initial value comes to the UI as false or null. if the value is false or null, then my checkbox needs to be checked, and if the backend value comes in as true, then my checkbox needs to be unchecked. Using, Material UI checkbox
link to codesandbox: https://codesandbox.io/s/controlledcheckbox-material-demo-forked-3rv5z5?file=/demo.js
import * as React from 'react';
import Checkbox from '@mui/material/Checkbox';
export default function ControlledCheckbox() {
const [checked, setChecked] = React.useState(false);
const handleChange = (event) => {
setChecked(event.target.checked);
};
console.log('checked: ', checked);
return (
<Checkbox
checked={checked === false ? true : checked}
onChange={handleChange}
inputProps={{ 'aria-label': 'controlled' }}
/>
);
}
CodePudding user response:
What you could do is begin with a React useEffect to do a backend query to get the current state of the checkbox. Then, if it turns out to be true, you can call your state hook and do a setChecked(true) that will automatically change the state to true. Hope that helps!
CodePudding user response:
you can just use
checked = {checked}.
refer: https://codesandbox.io/s/controlledcheckbox-material-demo-forked-igg9h2