Since I started using react, there was always a dilemma for handling errors while validating input field values in the form more conveniently and easily.
So let's hear the story ( You can skip this and continue from the next paragraph π) behind using the react-hook-form in react - As I have a habit of building things on my own instead of looking for any library which helps us in understanding the actual things going on under the hood, so I started writing my functions to validate the input fields in the form and then conditionally show the errors below them. So now it was time to look for a library that can handle all these and reduce the number of code of lines and can be extensively flexible for more custom validations.
There are many libraries we can use to handle form input fields in react, and react-form-hook, formik are a few of them which I have explored, but in this blog, I will cover only react-hook-form.
Now Let's get started with implementing react-hook-form in our react project-
- At first, let's install all the dependencies required-
install npm i react-hook-form yup @hookform/resolvers
Here, we will be also using yup and yupResolver along with react-hook-form.
Yup is a JavaScript schema builder for value parsing and validation, for more information, click here
- Let's import them into our component
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
- Let's make schema validation using yup for the data to be entered in our input fields
For example, let's make a schema where the input fields will be-
1) name- which must be entered by the user and display an error message when it's not entered
2) email address- which must be entered and validated upon whether it's a valid email or not and display error accordingly
The schema for the aforesaid conditions will be -
const schema = yup.object().shape({
name: yup.string().required("Name is required!"),
email: yup
.string()
.email("Email should be valid!")
.required("Email is required!")
});
And our component looks something like this-
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
export default function App() {
const schema = yup.object().shape({
name: yup
.string()
.required("Name is required!"),
email: yup
.string()
.email("Email should be valid!")
.required("Email is required!")
});
return (
<div>Sign Up</div>
)
}
- Now we will be implementing the schema in our useForm hook as follows-
const {
register,
handleSubmit,
formState: { errors }
} = useForm({ resolver: yupResolver(schema) });
register is a function which is returned by useForm for validating the particular input field and returns error in the errors object in formState
// input field for name <input {...register(name)} /> // input field for email <input {...register(email)} />
errors message of a part input field is saved as -
// for errors in name errors.name.message // for errors in email errors.name.email
- After adding the code for register function and displaying errors(if any), our component will look like-
import "./styles.css";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
export default function App() {
const schema = yup.object().shape({
name: yup.string().required("Name is required!"),
email: yup
.string()
.email("Email should be valid!")
.required("Email is required!")
});
const {
register,
handleSubmit,
formState: { errors }
} = useForm({ resolver: yupResolver(schema) });
const onSubmit = (data) => {
console.log(data);
};
return (
<div className="App">
<h1>Sign Up</h1>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="flex-col">
<input
autoComplete="off"
{...register("name")}
id="name"
placeholder="Enter Name"
className="input"
/>
{errors.name && <div className="error">{errors.name.message}</div>}
<input
autoComplete="off"
type="email"
{...register("email")}
id="email"
placeholder="Enter Email"
className="input"
/>
{errors.email && <div className="error">{errors.email.message}</div>}
<input type="submit" className="button" value="Submit"/>
</div>
</form>
</div>
);
}
- Before submitting any form data, our form will look like as follows-
- Let's check our form validation and try to submit our form data-
- Oops! We forget to enter any data, and hurray! The form validation is working perfectly and showing the desired error messages too
Let's try to enter invalid email and check whether it shows the correct data or not-
- Kudos π€― ! The email invalid message also working fine too ! π€©
β οΈThe user can submit the form data only when the data field satisfies all schema vaiidation
Congratulations! π₯³ Now you can easily use react-form-hook with yup in any react project for validating the fields in the form.
You can also check the source code of the above-mentioned example program, here-codesandbox
Still have any queries, feel free to drop in the comment section π¬
Would be happy to know if this helped in understanding react-form-hook π