Thomazzz
Thomazzz

Reputation: 203

React Hook Forms + Material UI Checkboxes + FormControlLabel don't recieve default value

I am using React Hook Forms and I want to send in the processing to receive the Checkbox value, which is set to true by default I register the component, everything is fine, but if I do not touch anything (although the value of the checkbox is set to true), I get undefined, but as soon as I manually change the value of the checkbox, then it will be transmitted normally. Tell me how is the assigned value?

const { register, handleSubmit } = useForm();

const MyOnSubmit = (data) => {
  console.log(data);
};

const [checkemail, setcheckemail] = useState(true);

<form onSubmit={handleSubmit(MyOnSubmit)}>
  <FormControlLabel
    value={checkemail}
    control={<Checkbox defaultChecked color="primary" />}
    label="Ok"
    {...register('check')}
    onClick={(e) => {
      setcheckemail(e.target.checked);
    }}
  />

  <Button type="submit" color="primary"> 
    Sign Up
  </Button>
</form>

The checkbox is set by default, and if I don't change it manually and click on the submit form button, I get check = undefined

If I manually set the checkbox or uncheck it, then the value will be transmitted normally

Why? How to get the default checkbox value to be passed

Upvotes: 2

Views: 9226

Answers (2)

DINA TAKLIT
DINA TAKLIT

Reputation: 8388

Here is the correct way to use Checkbox with react-hook-form

import { useForm, Controller } from "react-hook-form";
import {
  Checkbox,
  FormControlLabel,
} from "@mui/material";

const { handleSubmit, control } = useForm()
...

<Controller
  control={control}
  name={`${item.id}`}
  defaultValue={!!evaluationDimensions?.[item.id]?.selected} 
  render={({ field: { onChange, value } }) => (
    <FormControlLabel
      control={
        <Checkbox
          checked={value}
          onChange={onChange}
        />
      }
    />
  )}
/>
...

Make sure to defaultValue whenever you use checked={value} to prevent issues such

React warning MUI: A component is changing the default checked state of an uncontrolled SwitchBase after being initialized

Upvotes: 0

Mahadev Bk
Mahadev Bk

Reputation: 524

Please try this code by replacing useForm and FormControlLabel. It should work

const {register, handleSubmit, control  } = useForm();

  <FormControlLabel
        label={"Ok"}
        control={
          <Controller
            name="check"
            control={control}
            defaultValue={true}
            value={checkemail}
            render={({ field }) => <Checkbox {...field} defaultChecked />}
            onClick={(e) => {
              setcheckemail(e.target.checked);
            }}
          />
        }
      />

Please refer https://react-hook-form.com/get-started#IntegratingControlledInputs

Upvotes: 4

Related Questions