React Hooks For Form Validation – useForm

Category: Featured , Form , React
Author:react-hook-form
Views Total:12 views
Official Page:Go to website
Publish Date:September 11, 2020
License:MIT

A set of React hooks for performant, flexible, and extensible forms with easy to use validation.

Install & Import:

# NPM
$ npm i react-hook-form –save

import React from ‘react’;
import { useForm } from ‘react-hook-form’;

Basic usage:

function App() {
  const { register, handleSubmit, errors } = useForm(); // initialize the hook
  const onSubmit = (data) => {
    console.log(data);
  };
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstname" ref={register} /> {/* register an input */}
      <input name="lastname" ref={register({ required: true })} />
      {errors.lastname && 'Last name is required.'}
      <input name="age" ref={register({ pattern: /\d+/ })} />
      {errors.age && 'Please enter number for age.'}
      <input type="submit" />
    </form>
  );
}

Preview:

React Hooks For Form Validation - useForm

You Might Be Interested In:

Leave a Reply