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

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: /^\S+@\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

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