React 18 Hook Form Reset / Clear Form Values and Errors Tutorial

Last Updated on by in React JS

React form reset tutorial; Forms are handy provides the best possible way to get information from users.

A form is made of multiple input fields, which are placed in a form to extract data from users.

We have talked a lot about creating forms; however, we will enumerate the process of resetting the form values and errors in React application.

This tutorial will explain every possibility that will help you build a form, validate a form and make the default form values clear on click of a button.

You will see how to incorporate some of the conventional packages to create the form in React.

Including React hook form and yup libraries. Moreover, we will display the usage of React hooks such as useState, and useEffect.

Every element will be spewed during the persuasion process; at the end of this tutorial.

You will utterly understand how to clear default form values and errors in React application using external packages.

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 3: Build React Hook Form Component
  • Step 4: Update App Js File
  • Step 5: Run Development Server

Build New React App

If a new app is not created yet, go ahead and install the new React application.

You have to execute the given command from the command line tool:

npx create-react-app sky-app

Next, move into the app folder:

cd sky-app

Install React Hook Form Package

React hook form offers easy methods and APIs that make you manage the form very easily in React ecosystem.

From the command prompt, you have to run the following command.

npm install @hookform/resolvers --legacy-peer-deps

Install Yup Package

Now, we need to install the more package. The yup library, this library offers the JavaScript schema builder that helps in value parsing and validation.

npm install yup --legacy-peer-deps

Build React Hook Form Component

We need a basic form that will be invoked using yup, useForm, and yupResolver modules.

These packages are required to create and validate the form.

Also, we will show you how to use the React hooks to initialize and manage the state of the form.

Further, go to component/ folder, and make the MyForm.js file.

Then, you have to add the given code example 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>
  )
}

Update App Js File

Now, you have to open the App.js file and update this file with the new component that you 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>
  )
}

Run Development Server

The app is almost ready, apparently you need to start the react app. For that, you require to execute the given command.

npm start

If creating app locally, here is the url, that you can use to view the app.

http://localhost:3000

React Hook Form Reset / Clear Form Values and Errors Tutorial

Conclusion

In this tutorial, we discussed how to clear default values of input controls.

Not just the single input control, but we also uncovered the process and helped you reset a form using react hooks.

So, this was it; the react-hook-form reset default values and error messages tutorial is over.