Building ReactForm with React HookForm,Zod and ZodResolve
Forms are an essential part of many applications so in this section, you will learn how to build forms with React and a couple of third-party libraries We will be using react hook forms for managing form state and Zod for data validation As our form becomes more complex managing the form state with the state hook becomes complex time consuming and error-prone. The traditional way of managing the form state is as show below
import { useState } from "react";
const MyComponent = () => {
const [formData, setFormData] = useState({
fullName: "",
});
const handleChange = (e) => {
setFormData({
...formData,
fullName: e.target.value,
});
};
return (
<div className="mt-2">
<input
value={formData.fullName}
onChange={handleChange}
type="text"
id="full_name"
/>
</div>
);
};
export default MyComponent;
import { useForm } from "react-hook-form"
const { register } = useForm()
We import our custom hook, useForm, and create an object. The useForm has a lot of properties such as register to register input forms,reset to reset the field, etc. We destructure the object and grab the register prope For every input field, we have to set 2 attributes, the onChange, and the value attribute. This is where we can use a popular react library called a hook form. With this library, we can quickly build more forms with less code.
we will head to the terminal and type Npm install react-hook-form
An imaginary is our new web animation library that redefines what you thought was possible on the web. Hand-written in optimized WASM, Animaginary can even animate the height
property of an element at 60fps.
<input {...register("full_name"} type="text" id = "full_name/>
And instead of setting the onChange and value property, we will type braises then call the register function and give it a key like full_name The register function returns an object so when you spread them, all the properties will be added to the input field.
const { register } = useForm()
return(
<form onSubmit = {handleSubmit((data) => console.log(data))}
className="w-full flex flex-col space-y-2"
>
)
We also have to destructure the handleSubmit from the useForm property . When we are ready to use the handleSubmit , we have to reference it in the onSubmit form property and pass a submit handler as an argument and a submit handler is just a function that receives the data in the form
const Onsubmit = (data :FieldValues) =>{
console.log(data)
}
const { register } = useForm()
return(
<form onSubmit = {handleSubmit((data) => console.log(data))}
className="w-full flex flex-col space-y-2"
>
)
Also in real-world applications, there are more involved in just logging the data on the console so we want to implement that logic in a separate function like Onsubmit,the data parameter will be a data field type that is defined in the react-hook-form library.
NB: the onSubmit function outside the form must not have the same name as the onSubmit form property in the form.We choose the same name for descriptive purposes, you can call your function any name eg. submit
Now let's talk about applying validation rules, let's say as part of submitting the form you want to make sure the user enters a value for the name field, and the value should be at least 3 characters long
So you go to where you are registering our name field and add a second argument which is an object and in this object, we can add the standard HTML attribute for data validation, for example, we can set minLength to 2 and required to true .
Now let's talk about applying validation rules, let's say as part of submitting the form you want to make sure the user enters a value for the name field, and the value should be at least 3 characters long
So you go to where you are registering our name field and add a second argument which is an object and in this object, we can add the standard HTML attribute for data validation, for example, we can set minLength to 2 and required to true
<input {...register("full_name", required : true, minLength:2}
type = "text"
id = "full_name"
/>
Now we have to display the error message to the user, we grab the formstate property from the useForm , now this formstate returns an object that includes properties such as errors, isLoading,isSubmitted ,etc,now we are going to destructure the error property from the formstate.
const { register, handleSubmit, formState:{ errors },} = useForm();
<div>
<input {...register("full_name", required : true, minLength:2}
type = "text"
id = "full_name"
/>
{errors.full_name?.type === "required" && (<p>The name of the field is required</p>)}
{errors.full_name?.type === "minLength" && (<p>The name must be at least 3 characters</p>)}
</div>
Currently, we have validation rules in the middle of our markup and as our form gets complex,we will end up with validation rules all over the place it will be better to use a technique called schema based validation.
We have a lot of validation libraries like zod So we will learn how to integrate zod with react-hook-form we will start by installing zod Npm install zod t ap on this link to read the full article on medium [https://medium.com/@psam64850/building-reactform-with-react-hookform-zod-and-zodresolver-a2688023dea1]