React Hook Form is a popular library for managing forms in React applications. It allows you to build forms with minimal boilerplate code and provides features like form validation, handling form state, and more. Here's a basic guide on how to work with React Hook Form:
Installation
First, install React Hook Form using npm or yarn:
# using npm
npm install react-hook-form
# using yarn
yarn add react-hook-form
Basic Usage
- Import the necessary components and hooks:
import React from 'react';
import { useForm, Controller } from 'react-hook-form';
- Set up the form and its inputs using the
useForm
hook:
function MyForm() {
const { control, handleSubmit } = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
{/* form inputs go here */}
<button type="submit">Submit</button>
</form>
);
}
Controlled Inputs with Controller
React Hook Form uses the Controller
component to wrap your form inputs and handle their state. Here's an example with an input field:
function MyForm() {
const { control, handleSubmit } = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>Name:</label>
<Controller
name="name"
control={control}
defaultValue=""
render={({ field }) => <input {...field} />}
/>
<button type="submit">Submit</button>
</form>
);
}
Form Validation
You can easily add validation rules to your form fields. React Hook Form provides built-in validation or you can use external libraries like Yup.
import * as yup from 'yup';
const schema = yup.object().shape({
name: yup.string().required('Name is required'),
});
function MyForm() {
const { control, handleSubmit } = useForm({
resolver: yupResolver(schema),
});
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>Name:</label>
<Controller
name="name"
control={control}
defaultValue=""
render={({ field, fieldState }) => (
<div>
<input {...field} />
{fieldState.error && <p>{fieldState.error.message}</p>}
</div>
)}
/>
<button type="submit">Submit</button>
</form>
);
}
This is just a basic overview of using React Hook Form. The library provides many other features like conditional rendering, custom hooks, and more. Be sure to check the official documentation for more in-depth information and examples.