Site icon RemoteStack

How to Reset Form Values and Error Messages in React Js

Building simple or advanced form in React is pretty easy, thanks to React hook form package. This package makes the form creation process facile; In our previous guides, we have seen how to work with React Hook Forms.

In this tutorial, we will learn how to reset the form’s default values and error messages in the React application. We will start with building a basic form in the stateless component. Afterwards, we will set the state, update the state in relation to reset the form.

To reset the form, we will use the flamboyant reset method offered by the useForm() object. This method is used to reset form state and values. You can reset only the tiny part of the form state or reset or clear the complete form.

With Reset, you profoundly retain the form state. Here are the options that you might need to handle the form reset state.

React Hook Form Reset Form Values and Error Messages Example

Generate React Project

In this step, you will learn to generate a new app. Open the command-line tool, type the command and hit enter to start installing the app.

npx create-react-app react-mercury

Add React Hook Form with Yup Packages

Head over to the code editor’s command-line tool, copy the given commands and type them on the console’s screen, then hit enter to add both the libraries.

npm install yup
npm install @hookform/resolvers

Create React Hook Form Component

Upto this point, you have created the new project and added the libraries enough.

This step will reveal how to build a new component that will be used for form handling.

Next, make the brand new ReactHookForm.js file within the component/ folder.

Ensure that you are importing the react hooks, form packages and form validation schema packages.

Update the code in ReactHookForm.js file.

import React, { useState, useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'
import * as Yup from 'yup'

export default function ReactHookForm() {
  // Define validaiton
  const formSchema = Yup.object().shape({
    name: Yup.string()
      .required('Name is required')
      .min(4, 'Enter least 4 characters'),
    email: Yup.string().required('Email is required').email(),
  })

  const rfcResolver = { resolver: yupResolver(formSchema) }

  // Set react hook form
  const { register, handleSubmit, reset, formState } = useForm(rfcResolver)

  // Destruct errors
  const { errors } = formState

  // init state
  const [profile, setProfile] = useState(null)

  // Perform side effect after component mount
  useEffect(() => {
    setTimeout(
      () =>
        setProfile({
          name: 'Romi',
          email: 'romi@gmail.com',
        }),
      1050,
    )
  }, [])

  // Evoke side effect on component update
  useEffect(() => {
    reset(profile)
  }, [profile])

  // Submit form
  function onFormSubmit(val) {
    console.log(val)
    return false
  }

  return (
    <div>
      <h2>React Reset Form Values and Errors Example</h2>

      <form onSubmit={handleSubmit(onFormSubmit)}>
        <div className="form-group mb-2">
          <label>
            <strong>Name</strong>
          </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">
          <label>
            <strong>Email</strong>
          </label>
          <input
            name="email"
            type="text"
            {...register('email')}
            className={`form-control ${errors.email ? 'is-invalid' : ''}`}
          />
          <div className="invalid-feedback">{errors.email?.message}</div>
        </div>
        <div className="d-grid">
          <button type="submit" className="btn btn-dark mt-3 mb-3">
            Submit
          </button>

          <button
            type="button"
            onClick={() =>
              reset({
                name: '',
                email: '',
              })
            }
            className="btn btn-danger"
          >
            Reset
          </button>
        </div>
      </form>
    </div>
  )
}

In functional components, state and side effects are managed by hooks. Make sure to import at the top of the component file.

Import useForm and Yup to create and validate the form.

We will use the useEffect hook and useForm’s reset value to set the form on component update.

Moreover, use the reset() method to clear the form’s initial and entered values. Please, notice that the form error will also be cleared once you click on the reset button.

Register Form Component in App

In order to harness the power of the form component, we have to import the react hook form component in the App.js file.

Presumably, you have to include the code into your app js file.

import React from 'react'

import 'bootstrap/dist/css/bootstrap.min.css'
import ReactHookForm from './components/ReactHookForm'


export default function App() {
  return (
    <div className="container mt-5">
      <ReactHookForm />
    </div>
  )
}

Start React App

Running a react app is not rocket science; it just takes a small command to be typed and executed through the command panel.

We are sure you have opened the command line tool in your code editor, just copy and paste the given command and hit enter.

npm start

Summary

In this short guide, we shed light on the working mechanics of React Hook Form’s reset method. We have, step by step, uncovered all the details that help us to build the form component with React useEffect hook.

We didn’t just create the standard form; instead, we learned how to create and display the validation errors in the form. Most importantly, we discovered how to set the default values of the form and clear or reset the default values of the form.

Exit mobile version