Using React Hook Form with Material UI

Created Updated
2 min read 399 words

React Hook Form is an excellent library for managing forms in a lightweight and efficient way. It has built-in support for many popular form libraries including Material UI. However, when using the two libraries together, it’s important to note that you need to wrap the MUI input component with the `Controller` component provided by React Hook Form in order for errors to be properly handled.

The Problem

When using MUI components directly within your form fields, you may notice that errors are not being displayed correctly (or at all) even though they have been registered with React Hook Form via its validation rules or schema.This happens because of how hook-form tracks field values: since material-ui components such as TextField etc.. don’t expose their value property like regular HTML inputs do (instead relying on internal state management), react-hook-form cannot automatically watch them without additional configuration.

The Solution

To solve this issue we can use the `Controller` component from react-hook-form which provides a wrapper around third-party input components like those found in MUI so that they can be tracked just like any other standard input element:

  1. Import the necessary modules:
import { useForm, Controller } from "react-hook-form";
import TextField from "@mui/material/TextField";
  1. Create your form object and define your validation rules/schemas if needed:
const { control, handleSubmit } = useForm({
	// Your options/rules...
});
  1. Wrap each of your individual MUI input fields inside a `<Controller>` tag instead of directly rendering them into our JSX markup:
<form onSubmit={handleSubmit(onSubmit)}>
	<Controller
		name="firstName"
		control={control}
		defaultValue=""
		rules={{ required: true }}
		render={({ field, fieldState }) => (
			<TextField
				{...field}
				label="First Name"
				error={!!fieldState.error} // Material UI expects this to be a boolean
				helperText={fieldState?.error?.message}
			/>
		)}
	/>
	{/* Repeat for all other fields */}
</form>
  1. In this example we used the Controller component provided by react-hook-form to wrap our TextField from MUI and pass it all necessary props including validation rules and default value. By doing so, any errors detected during submission will now show up on-screen (e.g., via the helperText prop) without requiring additional configuration or modifications of your existing markup!

Conclusion

Using React Hook Form with Material UI is an excellent way to manage forms in your React applications. By following these simple steps you can ensure that your form components are properly tracked by hook-form and that errors are displayed as expected using MUI’s built-in error handling features!Thanks for reading!

References

Add comment below...

Please refresh the page if commenting system is not visible.