how to use react-hook-form in react with mui 5

How to Use react-hook-form in React with MUI 5

updated 22/11/23 By frontendshape

In this tutorial, we'll learn how to set up and install react-hook-form in a React Material UI 5 project. Before we begin, make sure you have React MUI 5 installed and configured.

Install & Setup Vite + React + Typescript + MUI 5


Install React MUI 5 With React Hook Form

To install react-hook-form alongside React MUI 5, use the following command.

npm install @mui/material @emotion/react @emotion/styled react-hook-form 

or

npm install react-hook-form


Create a form with validation using React MUI 5 and react-hook-form.

import { useForm } from 'react-hook-form';
import { TextField, Button, Container } from '@mui/material';

function App() {
  const { register, handleSubmit, formState: { errors } } = useForm();

  const onSubmit = data => {
    console.log(data); // 
  };

  return (
    <Container style={{ marginTop: "20px" }}>
      <form onSubmit={handleSubmit(onSubmit)}>
        <TextField
          label="Email"
          variant="outlined"
          fullWidth
          margin="normal"
          {...register("email", { required: "Email is required" })}
          error={Boolean(errors.email)}
          helperText={errors.email?.message}
        />
        <Button type="submit" variant="contained" color="primary">
          Submit
        </Button>
      </form>
    </Container>
  );
}

export default App;
add react-hook-form react mui 5

add react-hook-form react mui 5