Ebadta
Ebadta

Reputation: 367

latest react-hook-form error handling with material-ui TextField

I have difficulties, using react-hook-form with material-ui.

I prepared a codesandbox example.

import { TextField } from "@material-ui/core";
import React from "react";
import { useForm } from "react-hook-form";
import "./styles.css";

interface IMyForm {
  vasarlo: string;
}

export default function App() {
  const {
    handleSubmit,
    formState: { errors },
    register
  } = useForm<IMyForm>();

  const onSubmit = (data: IMyForm) => {
    alert(JSON.stringify(data));
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label>First Name</label>
      <TextField
        variant="outlined"
        margin="none"
        label="Test"
        {...register("vasarlo", {
          required: "error text"
        })}
        error={errors?.vasarlo ? true : false}
        helperText={errors?.vasarlo ? errors.vasarlo.message : null}
      />
      <input type="submit" />
    </form>
  );
}

How can I properly use the register function, to get error message, write to input field, also the onSubmit function to work?

I couldn't find answer in the documentation for this scenario.

Upvotes: 9

Views: 14529

Answers (2)

NearHuscarl
NearHuscarl

Reputation: 81310

In react-hook-form v7, this is how you register an input:

<input {...register('name')} />

Calling register() will return necessary props for your input like onChange, onBlur and ref. These props make it possible for react-hook-form to keep track of your form data. Now when you use register with Material-UI TextField like this:

<TextField {...register('name')} />

You pass the ref property directly to the TextField while the correct place to put it is in the inputRef:

<TextField inputRef={ref} />

So you have to modify your code like this:

const { ref: inputRef, ...inputProps } = register("vasarlo", {
  required: "error text"
});
<TextField inputRef={inputRef} {...inputProps} />

How can I properly use the register function, to get error message

There is nothing wrong with your error handling code. Though you can shorten you code a bit more using Typescript's optional chaining operator ?.:

<TextField
  error={!!errors.vasarlo}
  helperText={errors?.vasarlo?.message}
  inputRef={ref}
  {...inputProps}
/>

Live Demo

Edit 67009085/latest-react-hook-form-error-handling-with-material-ui-textfield

Upvotes: 16

acaputo
acaputo

Reputation: 300

You're misusing Controller. react-hook-form's default functionality is using uncontrolled inputs. Remove <Controller/> and put this on your TextField

inputRef={register({
    required: 'This is required',
    validate: (data) => myValidationFunction(data)
})}

You'll only want to use a controller if you NEED to modify/intercept/format a value that is being displayed in the TextField that is different from what a user is typing, i.e a phone number getting shown as (xxx)-xxx-xxxx when only typing the digits.

Upvotes: 1

Related Questions