How to use react-hook-form with ant design or material UI

Sang Dang picture Sang Dang · Nov 13, 2019 · Viewed 13.2k times · Source

I'm trying to use react-hook-form library to validate a form. When I render view using ant design or material UI, it does not work correctly.

<Input name="firstName" ref={register({ required: true })} />
  {errors.firstName && 'First name is required'}

Some warning happened: "Missing name at.....".

Answer

Samshel picture Samshel · Nov 14, 2019

For Material-UI you can pass register through the TextField component prop inputRef (I'm also using Yup for validation schemas)

import React, { useState } from 'react';
import { Button, TextField } from '@material-ui/core';
import useForm from 'react-hook-form';
import { object, string } from 'yup';

const Form: React.FC = () => {
  const schema = object().shape({
    username: string().required('Username is required'),
    password: string().required('Password is required'),
  });
  const { register, handleSubmit, errors } = useForm({ validationSchema: schema });
  const onSubmit = (data: any) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <TextField
        name="username"
        error={!!errors.username}
        label="Username"
        helperText={errors.username ? errors.username.message : ''}
        type="email"
        inputRef={register}
        fullWidth
      />
      <TextField
        name="password"
        error={!!errors.password}
        label="Password"
        inputRef={register}
        helperText={errors.password ? errors.password.message : ''}
        type="password"
        fullWidth
      />

      <Button
        color="primary"
        type="submit"
        variant="contained"
        fullWidth
      >
        Submit
      </Button>
    </form>
  );
};