Arif hossain
Arif hossain

Reputation: 489

Material ui Checkbox is not working in React-hook form

I want to make a Form with validation for that I used react-hook-form with Material UI. And for validation, yup and hook/resolver are also used. when I click the Checkbox I want to show another textField but the checkbox is not working. watch is used for that which comes from react-hook-form(useForm). what is my mistake? plz, help.

Here is my code: - codesanbox

Upvotes: 3

Views: 5535

Answers (2)

Jerome
Jerome

Reputation: 2761

for those who are struggling with MUI5, NextJs 12 and RHF 7 in typescript, here is how I make it working

Please note that the RHF Controller is inside the FormControlLabel and not the opposite. Also the defaultValue matters

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

type ICheckBoxFieldProps = CheckboxProps & {
  name: string;
  control: Control;
  label: string;
};

const CheckBoxField: React.FC<ICheckBoxFieldProps> = ({
  name,
  control,
  label,
  defaultChecked,
  ...rest
}: ICheckBoxFieldProps): JSX.Element => {
  return (
    <FormControlLabel
      label={label}
      control={
        <Controller
          name={name}
          control={control}
          defaultValue={!!defaultChecked}
          render={({ field }) => (
            <Checkbox
              checked={field.value}
              onChange={field.onChange}
              {...rest}
            />
          )}
        />
      }
    />
  );
};

export default CheckBoxField;

and how to call it inside a form or a FormProvider

<CheckBoxField
        name="istrue"
        control={control}
        defaultChecked={true}
        label="isTrue"
        color="success"
      />

Upvotes: 1

Joris
Joris

Reputation: 2796

You've to use the Controller or useController for the MUI checkbox, for instance:

<Controller
    name="hasPhone"
    control={control}
    render={({ field }) => (
      <FormControlLabel
        control={
          <Checkbox
            defaultValue={data.hasPhone}
            defaultChecked={data.hasPhone}
            color="primary"
            onChange={(e) => field.onChange(e.target.checked)}
            checked={field.value}
          />
        }
        label="Do you have a phone"
      />
    )}
  />

👉🏻 https://codesandbox.io/s/practical-morning-v6yp1

Upvotes: 2

Related Questions