react-hook-form is a powerful library that simplifies the process of building and managing forms in React applications. It provides a minimal API, which allows for easy integration and better performance. With react-hook-form, we can validate form inputs, handle errors, and control form state efficiently, all while reducing the amount of code needed compared to traditional form handling methods.
and we can use that package just by running the following command:
npm i react-hook-form
These are the following topics that we are going to discuss:
Steps to Create the React Application
Step 1: Create a New React App
Create a new React app using the create-react-app command. Open your terminal and run:
npx create-react-app react-hook-form-demo
Step 2: Navigate into the project directory
cd react-hook-form-demo
Step 3: Run the following command
npm i react-hook-form
Project Structure:
project structureUpdated Dependencies:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.53.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
Step 4: Add the CSS
CSS
/* App.css */
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
font-family: Arial, sans-serif;
}
.container {
text-align: center;
padding: 20px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
border-radius: 8px;
background-color: #f9f9f9;
}
.header {
font-size: 24px;
color: #28a745; /* Green color for GeeksforGeeks */
margin-bottom: 20px;
}
To run our react application, use the below command:
npm start
Output: Open 'Localhost:3000' to see the output.
outputWe have used react-hook-form to handle form state and validation with basic HTML form elements. This is the simplest way to integrate react-hook-form and is ideal for beginners who want to focus on functionality without additional styling.
Syntax:
import { useForm } from 'react-hook-form';
function App() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm();
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<input {...register('firstName')} />
<input {...register('lastName', { required: true })} />
{errors.lastName && <p>Last name is required.</p>}
<input {...register('age', { pattern: /\d+/ })} />
{errors.age && <p>Please enter number for age.</p>}
<input type="submit" />
</form>
);
}
Example: Implementing Basic form handling with react-hook-form package..
JavaScript
// src/App.js
import React from 'react';
import { useForm } from 'react-hook-form';
import './App.css';
function App() {
// Setting up react-hook-form
const { register, handleSubmit, formState: { errors } } = useForm();
// Form submission handler
const onSubmit = (data) => {
alert(`Form submitted with data: ${JSON.stringify(data)}`);
};
return (
<div className="container">
<div className="header">GeeksforGeeks</div>
<form onSubmit={handleSubmit(onSubmit)}>
<input
{...register('firstName', { required: true })}
placeholder="First Name"
/>
{errors.firstName && <span>This field is required</span>}
<br /><br />
<input
{...register('lastName', { required: true })}
placeholder="Last Name"
/>
{errors.lastName && <span>This field is required</span>}
<br /><br />
<select {...register('gender')}>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br /><br />
<button type="submit">Submit</button>
</form>
</div>
);
}
export default App;
Output:
In this approach, we use controlled components along with react-hook-form. Controlled components explicitly manage their state via React's useState hook, while react-hook-form helps in validating and handling the form submission.
Example: Implementing Controlled Components with react-hook-form package..
JavaScript
//src/App.js
import React from 'react';
import { useForm, Controller } from 'react-hook-form';
import './App.css';
function App() {
// Setting up react-hook-form
const { control, handleSubmit } = useForm();
// Form submission handler
const onSubmit = (data) => {
alert(`Form submitted with data: ${JSON.stringify(data)}`);
};
return (
<div className="container">
<div className="header">GeeksforGeeks</div>
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
name="email"
control={control}
rules={{
required: "Email is required",
pattern: {
value: /^[a-zA-Z0-9._%+-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z]{2,4}$/,
message: "Please enter a valid email address ending in .com"
}
}}
render={({ field, fieldState: { error } }) => (
<>
<input {...field} placeholder="Email" />
{error && <span>{error.message}</span>}
</>
)}
/>
<br /><br />
<Controller
name="password"
control={control}
rules={{
required: "Password is required",
pattern: {
value: /^(?=.*[!@#$%^&*])/,
message: "Password must include a special character"
}
}}
render={({ field, fieldState: { error } }) => (
<>
<input type="password" {...field} placeholder="Password" />
{error && <span>{error.message}</span>}
</>
)}
/>
<br /><br />
<button type="submit">Submit</button>
</form>
</div>
);
}
export default App;
Output:
This approach uses uncontrolled components, where form data is managed by the DOM rather than React state. react-hook-form directly interacts with the form elements to manage state and validation.
Example: Implementing Uncontrolled Components with react-hook-form package..
JavaScript
// src/App.js
import React from 'react';
import { useForm } from 'react-hook-form';
import './App.css';
function App() {
// Setting up react-hook-form
const { register, handleSubmit, formState: { errors } } = useForm();
// Form submission handler
const onSubmit = (data) => {
alert(`Form submitted with data: ${JSON.stringify(data)}`);
};
return (
<div className="container">
<div className="header">GeeksforGeeks</div>
<form onSubmit={handleSubmit(onSubmit)}>
<input
{...register('username', { required: true })}
placeholder="Username"
/>
{errors.username && <span>This field is required</span>}
<br /><br />
<input
{...register('age', {
required: true,
valueAsNumber: true,
min: { value: 18, message: 'You must be at least 18' },
})}
placeholder="Age"
type="number"
/>
{errors.age && <span>{errors.age.message}</span>}
<br /><br />
<button type="submit">Submit</button>
</form>
</div>
);
}
export default App;
Output:
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. "Hello, World!" Program in ReactJavaScriptimport React from 'react'; function App() {
6 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides DOM-specific methods to interact with and manipulate the Document Object Model (DOM), enabling efficient rendering and management of web page elements. ReactDOM is used for: Rendering Components: Displays React components in the DOM.DOM Manipulation: Al
2 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsIn lists, React makes it easier to render multiple elements dynamically from arrays or objects, ensuring efficient and reusable code. Since nearly 85% of React projects involve displaying data collectionsâlike user profiles, product catalogs, or tasksâunderstanding how to work with lists.To render a
4 min read
React FormsForms play an Important role in applications, with 85% of web apps relying on them for collecting data, processing payments, and handling authentication. They are built using components like text fields, checkboxes, date pickers, and dropdowns. They often use controlled components to manage form sta
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. When rendering a list, you need to assign a unique key prop to each element in th
4 min read
Components in React
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects