How to Build the Next Generation of Forms with React Hooks Forms

How to Build the Next Generation of Forms with React Hooks Forms

Performant, flexible, and extensible forms, easy to use with validation by React Hooks

Drag and Drop Builder. You can build your own form with auto-generated code here at the React Hook Form Website. You will be able to re-arrange using drag and drop, delete, and edit each field to start using this incredible plugin, without having to read any documentation, simply by copying that code.

Why Not Other React Library Forms?

It’s really simple, there are multiple good reasons:

  1. Easy to adopt as form state is inherently local, it can be easily adopted without other dependencies.

  2. Reduces the code to handle forms, with less complexity due to the Hooks. You can find a complete code comparison here.

  3. Performance is important and package size matters. This is a tiny library without any dependencies.

  4. Minimizes the number of re-renders and faster mount, striving to provide the best user experience. Twenty times less than other packages like Formik or Redux Form

Installation

Installing React Hook Form only takes a single command and you’re ready to roll. If you are using npm:

npm install react-hook-form

Or, if you are using Yarn:

yarn add react-hook-form

Basic Usage

The following code will demonstrate basic usage.

The main component used is the useForm Hook with the returned functions and variables:

  • register: To connect a field to rules or validation functions.
  • handleSubmit: To check and validate all fields before sending submit.
  • watch: This will watch specified inputs and return their value.
  • errors: Contains form errors or error messages that belong to each input.
import React from 'react'
import useForm from 'react-hook-form'

export default function App() {
  const { register, handleSubmit, watch, errors } = useForm()
  const onSubmit = data => { console.log(data) }

  console.log(watch('example')) // watch input value by passing the name of it

  return (
    {/* "handleSubmit" will validate your inputs before invoking "onSubmit" */}
    <form onSubmit={handleSubmit(onSubmit)}>
    {/* register your input into the hook by invoking the "register" function */}
      <input name="example" defaultValue="test" ref={register} />

      {/* include validation with required or other standard HTML validation rules */}
      <input name="exampleRequired" ref={register({ required: true })} />
      {/* errors will return when field validation fails  */}
      {errors.exampleRequired && <span>This field is required</span>}

      <input type="submit" />
    </form>
  )
}

Register Fields

Each field needs a specific unique name that you will also use for labels and then you will pass the register Hook to the ref element.

Inside it, you will pass multiple parameters. Required is needed to tell if the user has to enter that field and then you will be able to easily use other standard HTML rules.

Here’s the list of validation rules supported:

  • required
  • min
  • max
  • minLength
  • maxLength
  • pattern
  • validate
import React from 'react'
import useForm from 'react-hook-form'

export default function App() {
  const { register, handleSubmit } = useForm()
  const onSubmit = data => console.log(data)

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstName" ref={register({ required: true, maxlength: 20 })} />
      <input name="lastName" ref={register({ pattern: /^[A-Za-z]+$/i })} />
      <input name="age" type="number" ref={register({ min: 18, max: 99 })} />
      <input type="submit" />
    </form>
  );
}

The validate function is a great way to use custom logic specific to that field, enabling you to implement custom behavior very easily.

<input
  name="single"
  ref={
    register({
      validate: (value) => value === '1'
    })
  }
/>

Handle Fields Errors

React Hook Form provides an errors object to show you the errors within the form related to each unique field.

import React from 'react'
import useForm from 'react-hook-form'

export default function App() {
  const { register, errors } = useForm()

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Input name="firstName" ref={register({ required: true })} />
      {errors.firstName && 'First name is required'}
      <Input name="lastName" ref={register({ required: true })} />
      {errors.lastName && 'Last name is required'}
      <input type="submit" />
    </form>
  );
}

Drag and Drop Builder

You can build your own form with auto-generated code here at the React Hook Form Website.

You will be able to re-arrange using drag and drop, delete, and edit each field to start using this incredible plugin, without having to read any documentation, simply by copying that code.

You can easily build a form like this one in less than one minute!

import React from 'react';
import useForm from 'react-hook-form';

export default function App() {
  const { register, handleSubmit, errors } = useForm();
  const onSubmit = data => console.log(data);
  console.log(errors);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input type="text" placeholder="First name" name="First name" ref={register({required: true, maxLength: 80})} />
      <input type="text" placeholder="Last name" name="Last name" ref={register({required: true, maxLength: 100})} />
      <input type="text" placeholder="Email" name="Email" ref={register({required: true, pattern: /^\[email protected]\S+$/i})} />
      <input type="tel" placeholder="Mobile number" name="Mobile number" ref={register({required: true, minLength: 6, maxLength: 12})} />
      <select name="Title" ref={register({ required: true })}>
        <option value="Mr">Mr</option>
        <option value="Mrs">Mrs</option>
        <option value="Miss">Miss</option>
        <option value="Dr">Dr</option>
      </select>

      <input name="Developer" type="radio" value="Yes" ref={register({ required: true })}/>
      <input name="Developer" type="radio" value="No" ref={register({ required: true })}/>

      <input type="submit" />
    </form>
  );
}

I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others. Thank you!

React React Hook Reactjs JavaScript Programming

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How native is React Native? | React Native vs Native App Development

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

Getting Started with React Hooks

Getting Started with React Hooks. When I first started learning React, there was one thing I knew for sure: If you want to use its state and lifecycle methods, you need to use class components — not functional components. According to the docs, hooks let you use state and other React features without writing a class.

React Hooks Tutorial for Beginners: Getting Started With React Hooks

React hooks tutorial for beginners, learn React hooks step by step: Introduction, useState Hook, useState with previous state, useState with object, useState with array, useEffect Hook, useEffect after render, Conditionally run effects, Run effects only once, useEffect with cleanup, useEffect with incorrect dependency, Fetching data with useEffect, useContext Hook, useReducer Hook, useReducer, Multiple useReducers, useReducer with useContext, Fetching data with useReducer, useState vs useReducer, useCallback Hook, useMemo Hook, useRef Hook

React Hooks — Should We Be Hooked on Hooks?

My opinion on the advantages of Hooks

React Slider: How to Build an Image Slider With React Hooks

React Slider: How to Build an Image Slider With React Hooks. Creation of all the components necessary to display an array of content, as well as the ability to navigate back and forth to each slide in our slider. Adding an autoplay feature. We will dive deeper into React Hooks and optimize the slider both for performance and visual appeal. We will achieve this by tapping into useEffect and some new memoization helpers.