简体   繁体   中英

how to use React-Hook-Form on Antd Input?

How can I use react-hook-form on antd inputs?

usually its like this

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    defaultValues: {
      firstName: "",
      lastName: "",
      email: "",
      phoneNumber: "",
      password: "",
    },
  });

  const onSubmit = (data) => console.log(data);

// Render
            <Input
              {...register("firstName")}
              className="my-2"
              placeholder="First Name *"
            />

it works ok with MUI Text Field but not with Antd Input.

i only get empty string;

I Would really appreciate some help

You can use Controller from 'react-hook-form' to wrap antd input.

Docs exampe

In your case it can be like this :

const App = () => {
  const {
    register,
    handleSubmit,
    control,
    formState: { errors }
  } = useForm({
    defaultValues: {
      firstName: "1",
      lastName: "",
      email: "",
      phoneNumber: "",
      password: ""
    }
  });

  return (
    <div className="App">
      <h1>antd version: {version}</h1>
      <Form>
        <Form.Item label="first name">
          <Controller
            name="firstName"
            control={control}
            render={({ field }) => (
              <Input {...field} className="my-2" placeholder="First Name *" />
            )}
          />
        </Form.Item>
      </Form>
    </div>
  );
};

Sounds like you need to create a controlled input. You can view the documentation here: https://react-hook-form.com/api/usecontroller

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM