Karina
Karina

Reputation: 23

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


Upvotes: 1

Views: 2860

Answers (4)

Let
Let

Reputation: 60

This is the code you are looking for:

export default function ControlledCheckbox() {
 const [checked, setChecked] = React.useState(false);

 const handleChange = (event) => {
   setChecked(prevCheck => !prevCheck);
 };

 console.log("checked: ", checked);
 return (
   <Checkbox
     checked={!checked}
     onChange={handleChange}
     inputProps={{ "aria-label": "controlled" }}
   />
  );
}

Upvotes: 0

DINA TAKLIT
DINA TAKLIT

Reputation: 8418

If you are using Checkbox without controller you can use defaultChecked={true} if you are using the Checkbox with react-hook-form use defaultValue instead to set it to true

<Controller
  control={control}
  name='selectItem'
  defaultValue={true} 
  render={({ field: { onChange, value } }) => (
    <FormControlLabel
      control={
        <Checkbox
          checked={value}
          onChange={onChange}
        />
      }
    />
  )}
/>

Upvotes: 0

Hari Prasad
Hari Prasad

Reputation: 491

you can just use

checked = {checked}.

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

Upvotes: 2

Kevin L Xu
Kevin L Xu

Reputation: 188

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!

Upvotes: 0

Related Questions