logo

Education

The Ultimate Guide to Integrating React Hook Form with Material UI

Authore Name
Sanket Shah

Software Development Executive - II

Last updated onAug 5, 2024

React Hook Form is a library that simplifies creating forms in React applications. It provides a set of hooks that help manage form state, validation, and submissions. When combined with Material UI, a popular React UI framework, developers can create accessible and visually appealing forms with ease. Integrating React Hook Form with Material UI ensures developers can handle forms efficiently while maintaining a consistent design language.

Setting Up the Environment

Installing React Hook Form and Material UI

To start using React Hook Form with Material UI, you must install both libraries in your React project. You can do this by running the following commands in your terminal:

1npm install @material-ui/core 2npm install react-hook-form 3

Creating a Basic React Component

Once the installations are complete, you can create an essential React component to demonstrate the usage of forms. For example:

1import React from 'react'; 2import { useForm } from 'react-hook-form'; 3import { TextField, Button } from '@material-ui/core'; 4 5function App() { 6 const { register, handleSubmit } = useForm(); 7 const onSubmit = data => console.log(data); 8 9 return ( 10 <form onSubmit={handleSubmit(onSubmit)}> 11 <TextField name="firstName" inputRef={register} label="First Name" /> 12 <Button type="submit">Submit</Button> 13 </form> 14 ); 15} 16 17export default App; 18

Importing Hooks and Components

In the above example, we import the necessary hooks (useForm) and components (TextField, Button) from the React Hook Form and Material UI libraries to create a simple form.

Creating Controlled Components with React Hook Form and Material UI

Controlled components are a key feature in React that allows you to manage the form data in the component's state. React Hook Form provides a Controller component to integrate controlled inputs with Material UI components.

1import { Controller } from 'react-hook-form'; 2 3function App() { 4 const { control, handleSubmit } = useForm(); 5 const onSubmit = data => console.log(data); 6 7 return ( 8 <form onSubmit={handleSubmit(onSubmit)}> 9 <Controller 10 as={TextField} 11 name="lastName" 12 control={control} 13 defaultValue="" 14 label="Last Name" 15 /> 16 <Button type="submit">Submit</Button> 17 </form> 18 ); 19} 20

In this example, the Controller component wraps the Material UI TextField to create a controlled component.

Implementing Form Validation and Error Handling

Defining Validation Rules

React Hook Form allows you to define validation rules easily using the register function. You can specify rules such as required, maxLength, and custom validation logic.

1const { register, handleSubmit, errors } = useForm(); 2const onSubmit = data => console.log(data); 3 4<TextField 5 name="email" 6 inputRef={register({ required: true, pattern: /^\S+@\S+$/i })} 7 label="Email" 8 error={!!errors.email} 9 helperText={errors.email ? "Email is required" : ""} 10/> 11 12

Displaying Validation Errors

Material UI components can be used to display error messages by utilizing the error and helperText props, which show validation feedback to the user.

Managing Form Submission and Data Handling

Setting Up a handleSubmit Function

The handleSubmit function from React Hook Form is used to process form submissions. It takes a callback function that will receive the form data if the form is valid.

1const { handleSubmit } = useForm(); 2const onSubmit = data => console.log(data); 3 4<Button type="submit" onClick={handleSubmit(onSubmit)}>Submit</Button> 5

Resetting Form Fields

React Hook Form's reset function can clear the form fields or set them back to default values after submission.

1const { reset } = useForm(); 2 3// Reset form to default values 4reset(); 5

Advanced Techniques and Custom Hooks

Creating Custom Input Components

You can create custom input components that integrate Material UI with React Hook Form by using the Controller component to wrap Material UI inputs.

Leveraging watch and control Features

The watch feature of React Hook Form allows you to subscribe to specific form fields and react to their changes. The control object is used to manage the registration of controlled components.

1const { control, watch } = useForm(); 2const gender = watch("gender"); 3 4<Controller 5 as={<TextField select />} 6 name="gender" 7 control={control} 8 defaultValue="female" 9 // ...other props 10/> 11

By following these steps and utilizing the features of React Hook Form and Material UI, developers can create robust, maintainable, and user-friendly forms in their React applications.

Advanced Techniques and Custom Hooks

Creating Custom Input Components

You can create custom input components that integrate Material UI with React Hook Form to enhance your forms further. This allows for more complex form structures and custom behaviors. Here's an example of how to create a custom input component using the Controller component to wrap a Material UI TextField:

1import React from 'react'; 2import { Controller, useForm } from 'react-hook-form'; 3import { TextField } from '@material-ui/core'; 4 5const CustomInput = ({ control, name, label }) => ( 6 <Controller 7 as={TextField} 8 name={name} 9 control={control} 10 defaultValue="" 11 label={label} 12 fullWidth 13 /> 14); 15 16function App() { 17 const { control, handleSubmit } = useForm(); 18 const onSubmit = data => console.log(data); 19 20 return ( 21 <form onSubmit={handleSubmit(onSubmit)}> 22 <CustomInput control={control} name="customInput" label="Custom Input" /> 23 <Button type="submit">Submit</Button> 24 </form> 25 ); 26} 27 28export default App; 29

Leveraging watch and control Features

The watch feature of React Hook Form allows you to monitor input values and react to their changes, which is helpful for conditional rendering or implementing dependent fields. The control object is essential for registering controlled components with the React Hook Form.

Here's an example of using a watch to display additional fields based on the selected gender:

1const { control, handleSubmit, watch } = useForm(); 2const gender = watch("gender"); 3 4return ( 5 <form onSubmit={handleSubmit(onSubmit)}> 6 <Controller 7 as={<TextField select />} 8 name="gender" 9 control={control} 10 defaultValue="" 11 label="Gender" 12 /> 13 {gender === 'other' && ( 14 <TextField 15 name="customGender" 16 label="Custom Gender" 17 inputRef={register} 18 /> 19 )} 20 <Button type="submit">Submit</Button> 21 </form> 22); 23

Form Submission and Data Handling

Processing Form Submissions

When the form is submitted, the handleSubmit function will invoke the onSubmit callback with the form's data if all validation rules pass. Here's how you can handle form submissions:

1const { handleSubmit } = useForm(); 2const onSubmit = data => { 3 console.log(data); 4 // Additional submission logic here 5}; 6 7<Button type="submit" onClick={handleSubmit(onSubmit)}>Submit</Button> 8

Handling Form Reset and Default Values

After submission, you should reset the form fields. React Hook Form's reset function can be used to clear the form or set fields back to their default values:

1const { reset } = useForm(); 2 3// Reset form to default values after submission 4handleSubmit((data) => { 5 console.log(data); 6 reset(); 7}); 8

Error Handling and Validation Feedback

Displaying Error Messages

The react Hook Form provides an error object that contains any validation errors. You can use this in conjunction with Material UI's TextField to display error messages:

1const { register, handleSubmit, errors } = useForm(); 2 3<TextField 4 name="email" 5 inputRef={register({ required: 'Email is required' })} 6 label="Email" 7 error={!!errors.email} 8 helperText={errors.email ? errors.email.message : ""} 9/> 10

Custom Validation Rules

You can define custom validation rules using React Hook Form's validate function. This allows you to create more complex validation logic that can be applied to your form inputs.

1const { register } = useForm(); 2 3<TextField 4 name="username" 5 inputRef={register({ 6 validate: value => value !== 'admin' || 'Username not available' 7 })} 8 label="Username" 9/> 10

Conclusion and Best Practices

Combining React Hook Form with Material UI provides a powerful solution for managing forms in React applications. Developers can create efficient, maintainable, and user-friendly forms by following the examples and techniques outlined in this guide. It's essential to remember best practices such as proper error handling, validation feedback, and performance optimization to ensure a smooth user experience. With these tools, you can tackle any form-related challenge in your React projects.

Short on time? Speed things up with DhiWise!

Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!

You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.

Sign up to DhiWise for free

Read More