React Hook Form

React Hook Form – build forms in React Native

Ina HranovaIna Hranova 3 minutes 159 views

Share:

React Hook Form is usefull Libary with built-in validation, perfomance and ease of use. It works with React as well as React Native. Another popular alternative library is Formik

We’ll show how to work with React hook Form by building a login form.

Installation

Now we need to install React Hook Form

npm i react-hook-form

or

yarn add react-hook-form

Let’s import the useForm hook.

import { useForm } from "react-hook-form";

We will need to add handleSubmitregister and errors:

const { register, handleSubmit, errors } = useForm();

To start, let’s create a  LoginForm component, with the email and password fields:

import React from "react";
import "./LoginForm.css";
const LoginForm = () => {
    return (
        <div className="login-form">
           <form>
            <label htmlFor="inputEmail">E-mail</label> 
            <input type="email" id="inputEmail" name="email" ref={register({ required: true })} /> 
            <label htmlFor="inputPassword">Password</label>
            <input type="password" id="inputPassword" name="password" ref={register({ required: true })} /> 
            <button type="submit">Login</button> 
           </form> 
        </div>
        );
    };
export default LoginForm;

Getting form data on submit

handleSubmit - it’s used to handle the form submission and get the filled data. Our onSubmit function will receive an object with the form’s data, that we can send to some backend api or do whatever we want with it.

const LoginForm = () => { 
const { register, handleSubmit, errors } = useForm(); 
    function onSubmit(data) {
      console.log("Data submitted: ", data);
     } 
return ( 
      <form onSubmit={handleSubmit(onSubmit)}> 
        //... campos do formulário 
</form> ); }

Validating and showing errors

If the input is an email, it return true. Otherwise, false.

<input
  type="email"
  name="email"
  ref={register({
    required: "Enter your e-mail",
    pattern: {
      value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
      message: "Enter a valid e-mail address",
    },
   })}
 />

We have two validations: required field (required) and a regular expression (pattern) to validate that the email is in the right format.

With that, the React Hook Form will prevent the form from being sent if any field fails validation.

Displaying Errors

For our example, we can add a conditional to each of the inputs and say if there is an error, we’ll set the borderColor to red.

<input
  type="email"
  name="email"
  ref={register({
    required: "Enter your e-mail",
    pattern: {
      value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
      message: "Enter a valid e-mail address",
    },
   })}
   style={{ ...styles.input, borderColor: errors.email && "red" }}
 />

You can find the documentation for the library at react-hook-form.com.

Happy Coding!