React Tutorial- Hook Form Reset/Clear Form Values And Errors

React Form Reset Tutorial

As we know already that a Form is made of multiple input fields which are placed in a form to extract data from the users.

Forms are a very crucial component of React Web applications. These allow the users to directly input and submit the data in components ranging from a login screen to a checkout page.

 

Throughout this guide, we will learn the process of resetting the form values and errors in React apps.

In this tutorial, we will learn everything from building a form, validating it and making the default form values clear on click of a button.

 

For doing so, we will have to install packages like React hook form and Yup libraries. We will also show the usage of React Hooks such as useState and useEffect.

 

How To Clear And Reset Errors And Form Values In React

Step 1- Build New React App

Step 2- Install React Hook Form Package

Step 3- Install Yup Package

Step 4- Build React Hook Form Component

Step 5- Update App Js File

Step 6- Run Development Server

 

Let’s learn in detail now:

Step 1- Build New React App

If you have already installed the new React application, then there is no need to follow this step. Otherwise, we need to execute the following command from the command-line tool:

npx create-react-app sky-app

Further, we move into the app folder:

cd sky-app

 

Step 2- Install React Hook Form Package

React Hook Form offers easy methods and APIs that make us manage the form very easily in React ecosystem.

From the command prompt, we have to run the given command:

npm install @hookform/resolvers

 

Step 3- Install Yup Package

Here, in this step, we have to install another package. The Yup library offers the Javascript schema builder that helps in value parsing and validation:

npm install yup

 

Step 4- Build React Hook Form Component

In this step, we will build React Hook form that will be invoked using yup, useForm and yupResolver modules.

We need these packages to create and validate the form. We will also learn how to use the React Hooks to initialize and manage the state of the form.

Afterward, we need to go to component/ folder for making the MyForm.js file. Then, we will add the following code in the file:

import React, { useState, useEffect } from 'react'
import * as Yup from 'yup'
import { useForm } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'
export default function MyForm() {
  
  const YupForm = Yup.object().shape({
    name: Yup.string()
      .required('This value is required')
      .min(3, 'Proivde atleast 3 chars'),
    email: Yup.string().required('Email required').email(),
  })
  const resolverForm = { resolver: yupResolver(YupForm) }
  const { register, handleSubmit, reset, formState } = useForm(resolverForm)
  const { errors } = formState
  const [user, userData] = useState(null)
  useEffect(() => {
    setTimeout(
      () =>
        userData({
          name: 'Henna',
          email: 'henna@abc.com',
        }),
      1050,
    )
  }, [])
  useEffect(() => {
    reset(user)
  }, [user])
  function onRHFSubmit(res) {
    console.log(res)
    return false
  }
  return (
    <div className="container mt-5">
      <h2>React Clear Form Values and Error Messages Example</h2>
      <form onSubmit={handleSubmit(onRHFSubmit)}>
        <div className="form-group mb-3">
          <label>Name</label>
          <input
            name="name"
            type="text"
            {...register('name')}
            className={`form-control ${errors.name ? 'is-invalid' : ''}`}
          />
          <div className="invalid-feedback">{errors.name?.message}</div>
        </div>
        <div className="form-group mb-3">
          <label>Email</label>
          <input
            name="email"
            type="text"
            {...register('email')}
            className={`form-control ${errors.email ? 'is-invalid' : ''}`}
          />
          <div className="invalid-feedback">{errors.email?.message}</div>
        </div>
        <button type="submit" className="btn btn-primary">
          Send
        </button>
        <button
          type="button"
          onClick={() =>
            reset({
              name: '',
              email: '',
            })
          }
          className="btn btn-info">
          Reset
        </button>
      </form>
    </div>
  )
}

 

Step 5- Update App Js File

Further, we will open the App.js file and update this file with the new component that we have to see in the browser:

import React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css'
import MyForm from './components/MyForm'
export default function App() {
  return (
    <div className="App">
      <MyForm />
    </div>
  )
}

 

Step 6- Run Development Server

Now, we have reached the end of the guide. So, we need to start the React app. For that, we will execute the given command:

npm start

 

Conclusion

So friends, in this React tutorial, we have learned how to clear default values of input controls, not just the single input control, but we saw the process of resetting a form using React Hooks.

Hence, it was the tutorial about the react-hook-form reset default values and error messages.

 

Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *