'React Checkbox default value to true

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' }}
    />
  );
}




Solution 1:[1]

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!

Solution 2:[2]

you can just use

checked = {checked}.

refer: https://codesandbox.io/s/controlledcheckbox-material-demo-forked-igg9h2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KevThatDevs
Solution 2 Hari Prasad