Written by: Geoffrey Callaghan
Making forms easier with react-hook-form
Making Forms Easier With React-Hook-Form
Using react-hook-form
can greatly simplify form handling in React applications by providing a clean, declarative way to manage form state, validation, and submission. Here’s a guide on how to use react-hook-form
to make forms easier in React.
First, you need to install react-hook-form
:
npm install react-hook-form
To start using react-hook-form
, you need to import and initialize it in your form component.
import React from 'react';
import { useForm } from 'react-hook-form';
const { register, handleSubmit, formState: { errors } } = useForm();
function MyForm() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = data => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label htmlFor="name">Name</label>
<input id="name" {...register('name', { required: true })} />
{errors.name && <span>This field is required</span>}
</div>
<div>
<label htmlFor="email">Email</label>
<input id="email" {...register('email', { required: true, pattern: /^[^@\s]+@[^@\s]+\.[^@\s]+$/ })} />
{errors.email && <span>Invalid email address</span>}
</div>
<button type="submit">Submit</button>
</form>
);
}
export default MyForm;
react-hook-form
provides robust validation features that can be added declaratively. You can use validation rules directly in the register
function.
function MyForm() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = data => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label htmlFor="username">Username</label>
<input id="username" {...register('username', { required: 'Username is required' })} />
{errors.username && <span>{errors.username.message}</span>}
</div>
<div>
<label htmlFor="password">Password</label>
<input id="password" type="password" {...register('password', { required: 'Password is required', minLength: { value: 6, message: 'Password must be at least 6 characters' } })} />
{errors.password && <span>{errors.password.message}</span>}
</div>
<div>
<label htmlFor="email">Email</label>
<input id="email" {...register('email', { required: 'Email is required', pattern: { value: /^[^@\s]+@[^@\s]+\.[^@\s]+$/, message: 'Invalid email address' } })} />
{errors.email && <span>{errors.email.message}</span>}
</div>
<button type="submit">Submit</button>
</form>
);
}
export default MyForm;
The handleSubmit
function provided by useForm
manages the form submission process. It ensures that validation is performed before calling your custom submit handler.
const onSubmit = data => {
console.log('Form Data:', data);
};
<form onSubmit={handleSubmit(onSubmit)}>
<!-- form fields -->
</form>
To reset the form, you can use the reset
function provided by useForm
.
const { register, handleSubmit, reset, formState: { errors } } = useForm();
const onSubmit = data => {
console.log(data);
reset(); // Reset form after submission
};
You can integrate react-hook-form
with UI libraries like Material-UI, Ant Design, etc., by using their components in place of standard HTML inputs and wrapping them with register
.
import React from 'react';
import { useForm } from 'react-hook-form';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
function MyForm() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = data => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<TextField
label="Name"
{...register('name', { required: 'Name is required' })}
error={!!errors.name}
helperText={errors.name?.message}
/>
</div>
<div>
<TextField
label="Email"
{...register('email', { required: 'Email is required', pattern: { value: /^[^@\s]+@[^@\s]+\.[^@\s]+$/, message: 'Invalid email address' } })}
error={!!errors.email}
helperText={errors.email?.message}
/>
</div>
<Button type="submit" variant="contained" color="primary">Submit</Button>
</form>
);
}
export default MyForm;
react-hook-form
makes handling forms in React simple and efficient. It provides powerful features for managing form state and validation while keeping the code concise and easy to read. Whether you are building simple forms or complex multi-step forms, react-hook-form
can help you manage the process effectively.