1
votes

I have a simple form with a single Material UI TextField inside React Hook Form. I use Yup schema validation (via yupResolver). I try to validate form and display errors visually (boolean prop 'error' in TextField). I use Controller with 'render' prop, however it fails to update error on TextField change. Does anyone know what I am doing wrong here?

Link to codesandbox

import React from "react";
import ReactDOM from "react-dom";
import { TextField } from "@material-ui/core";
import { Controller, useForm } from "react-hook-form";
import * as yup from "yup";

import { yupResolver } from "@hookform/resolvers/yup";
import "./styles.css";

const schema = yup.object().shape({
  title: yup.string().required("Required")
});

function App() {
  const {
    handleSubmit,
    formState: { errors },
    control
  } = useForm({
    resolver: yupResolver(schema)
  });

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        render={({ formState, fieldState }) => {
          return <TextField label="Title" error={!!formState.errors?.title} />; 
        }}
        name="title"
        control={control}
      />
      <input type="submit" />
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Additonally 'fieldState' in Controller seems to be an empty object all the time. Shouldn't it show properties as listed in Link

2

2 Answers

1
votes

I found the answer following @damjtoh suggestion. I've noticed there is a 'field' parameter in the render function in RHF code examples. Adding it to TextField connected component with the form. Just remember to add 'defaultValue' to avoid 'changing uncontrolled input' error. Here's how it should look like:

<form onSubmit={handleSubmit(onSubmit)}>
    <Controller
    render={({ field, formState }) => (
        <TextField
        {...field}
        label="Title"
        error={!!formState.errors?.title}
        />
    )}
    name="title"
    control={control}
    defaultValue=""
    />
    <input type="submit" />
</form>
0
votes

You aren't connecting the material-ui component to the react-hook-form, you should check the Integrating Controlled Inputs section of react-hook-form documentation.