У цій статті ми розглянемо бібліотеку reak-hook-form.
Ви дізнаєтесь, як використовувати та інтегрувати цю бібліотеку з React. Ми також побачимо, чому це стає популярним вибором для створення як простих, так і складних форм з доданою підтримкою для обробки складних перевірок.
Давайте розпочнемо
Робота з формами в React є складним завданням. І це просто ускладнюється, коли кількість полів введення збільшується разом із перевірками.
Погляньте на наведений нижче код:
import React, { useState } from "react"; import "./styles.css"; export default function App() { const [state, setState] = useState({ email: "", password: "" }); const handleInputChange = (event) => { setState((prevProps) => ({ ...prevProps, [event.target.name]: event.target.value })); }; const handleSubmit = (event) => { event.preventDefault(); console.log(state); }; return ( Email Password Login ); }
Ось демонстрація пісочниці коду: //codesandbox.io/s/login-form-zjxs9.
У наведеному вище коді ми маємо лише 2 поля введення, а саме email
та password
, та кнопку подання.
Кожне поле введення має доданий обробник value
та onChange
обробник, щоб ми могли оновити стан на основі вводу користувача.
Крім того, ми додали handleSubmit
метод, який відображає дані, введені у форму, на консоль.
Це виглядає чудово. Але що, якщо нам потрібно додати перевірки, такі як перевірка необхідного поля, перевірка мінімальної довжини, перевірка пароля, перевірка поля електронної пошти, а також відображення відповідних повідомлень про помилки?
Код стане більш складним і довгим із збільшенням кількості полів введення та їх перевірок.
Це дуже поширена вимога в будь-якій програмі. Так легко працювати з формами, існують різні бібліотеки , доступні як Formik
, redux-form
, react-final-form
, react-hook-form
і так далі.
Але те, що набуває великої популярності, - це react-hook-form
бібліотека.
Тож давайте тепер дізнаємось, чому і як ним користуватися. Для цього ми створимо новий додаток React.
Створіть новий проект React, виконавши з терміналу таку команду:
npx create-react-app react-hook-form-demo
Після створення проекту видаліть усі файли з src
папки та створіть нові index.js
та styles.css
файли всередині src
папки.
Щоб встановити бібліотеку форм, виконайте таку команду з терміналу:
yarn add react-hook-form
Як створити початкові сторінки
Відкрийте src/index.js
файл і додайте до нього такий вміст:
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(, document.getElementById('root'));
Відкрийте src/styles.css
файл і додайте вміст звідси всередину.
Тепер створіть App.js
у src
папці новий файл із таким вмістом:
import React from "react"; import "./styles.css"; export default function App() { return ( Email Password Login ); }
Тут ми щойно додали у форму поля електронної пошти та пароля.
Створення базової форми за допомогою реакційно-гачкової форми
react-hook-form
Бібліотека забезпечує useForm
гак , який ми можемо використовувати для роботи з формами.
Імпортуйте useForm
гачок таким чином:
import { useForm } from 'react-hook-form';
Використовуйте useForm
гачок так:
const { register, handleSubmit, errors } = useForm();
Ось,
- register - це функція, яка використовується як посилання, що надається
useForm
гачком. Ми можемо призначити його кожному полю введення, щоб вінreact-hook-form
міг відстежувати зміни для значення поля введення. - handleSubmit - це функція, яку ми можемо викликати при поданні форми
- помилки будуть містити помилки перевірки, якщо такі є
Тепер замініть вміст App.js
файлу таким вмістом:
import React from "react"; import { useForm } from "react-hook-form"; import "./styles.css"; export default function App() { const { register, handleSubmit, errors } = useForm(); const onSubmit = (data) => { console.log(data); }; return ( Email Password Login ); }
У наведеному вище коді ми вказали посилання на кожне поле введення, яке ми отримали з useForm
хука.
ref={register}
Крім того, ми додали функцію onSubmit, яка передається функції handleSubmit.
Зверніть увагу, що для кожного поля введення ми дали унікальну назву, яка є обов’язковою, щоб react-hook-form
можна було відстежувати зміни даних.
Коли ми подаємо форму, функція handleSubmit обробляє подання форми. Він надішле введені користувачем дані до функції onSubmit, яку ми реєструємо на консолі.
const onSubmit = (data) => { console.log(data); };
Тепер запустіть програму, запустивши yarn start
команду.

Як бачите, коли ми надсилаємо форму, введені користувачем дані відображаються на консолі.
Крім того, у порівнянні з кодом без react-hook-form
(який ми бачили на початку цієї статті), цей код набагато простіший. Це тому, що нам не потрібно додавати обробник value
і onChange
для кожного поля введення, і немає необхідності самостійно управляти станом програми.
Як додати перевірки до форми
Now, let’s add the required field and minimum length validation to the input fields.
To add validation we can pass it to the register function which is passed as a ref to each input field like this:
We also want to display the error message if the validation fails.
When the validation fails, the errors object coming from useForm
will be populated with the fields for which the validation failed.
Open the App.js
file and replace its contents with the following content:
import React from "react"; import { useForm } from "react-hook-form"; import "./styles.css"; export default function App() { const { register, handleSubmit, errors } = useForm(); const onSubmit = (data) => { console.log(data); }; return ( Email {errors.email && errors.email.type === "required" && ( Email is required.
)} {errors.email && errors.email.type === "pattern" && ( Email is not valid.
)} Password {errors.password && errors.password.type === "required" && ( Password is required.
)} {errors.password && errors.password.type === "minLength" && ( Password should be at-least 6 characters.
)} Login ); }

Here, for the email input field, we have provided the required and pattern matching validations.
So as you type in the email input field, the validation will run once the form is submitted.
If the validation failed, then the errors.email
field inside the errors object will be populated with the type field which we used to display the error message.
{errors.email && errors.email.type === "required" && ( Email is required.
)}
In the similar way, we have added the password field validation.
So as you can see, each input field is automatically focused if there is any validation error for the that input field when we submit the form.
Also, the form is not submitted as long as there is a validation error. You can see that the console.log
statement is only printed if the form is valid.
So using react-hook-form
reduced the amount of code that we have to write. The validation is also responsive, so once the field becomes valid, the error message goes away instantly.
But as the number of validations for each field increases, the conditional checks and error message code will still increase. So we can further refactor the code to make it even simpler.
Take a look at the below code:
import React from 'react'; import { useForm } from 'react-hook-form'; import './styles.css'; export default function App() { const { register, handleSubmit, errors } = useForm(); const onSubmit = (data) => { console.log(data); }; return ( Email {errors.email && {errors.email.message}
} Password {errors.password && ( {errors.password.message}
)} Login ); }
In the code above, we have changed the email and password validation code.
For the email input field, we changed this previous code:
to the below new code:
Here, we’ve directly provided the error message we want to display while adding the validation itself.
So we no longer need to add extra checks for each validation. We are displaying the error message using the message property available inside the errors object for each input field.
{errors.email && {errors.email.message}
}
So by doing it this way, the code is further simplified which makes it easy to add extra validations in future.
Note that if there are validation errors, the onSubmit handler will not be executed and the corresponding input field will automatically be focused (which is a good thing).
How to Add a Custom Validation Method
You can even provide a custom validation for the input field by adding a validate
method. This is useful if you need to perform complex validations like this:
// validation function const validatePassword = (value) => { if (value.length < 6) { return 'Password should be at-least 6 characters.'; } else if ( !/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s)(?=.*[[email protected]#$*])/.test(value) ) { return 'Password should contain at least one uppercase letter, lowercase letter, digit, and special symbol.'; } return true; }; // JSX

Now you know how to use react-hook-form
to create forms in React along with complex validations.
Why react-hook-form is better than the alternatives
Let’s look at some additional reasons that react-hook-form
should become your preferred choice for working with forms.
- Code complexity is less as compared to
formik
,redux-form
and other alternatives. react-hook-form
integrates well with theyup
library for schema validation so you can combine your own validation schemas.- The number of re-renders in the application is small compared to the alternatives.
- Mounting time is less as compared to the alternatives.
For the actual comparison metrics, read more here.
Conclusion
In this article, we have seen how to use react-hook-form
and why it's many developers' preferred choice for building both simple and complex forms in React.
You can find the GitHub source code for this application here.
If you liked this article, then you'll also love my other articles.
Subscribe to my weekly newsletter to join other 1000+ subscribers to get amazing tips, tricks, and articles directly in your inbox.