React Tutorial- Set/Reset Form Values With Hook Form And Hooks

Set/Reset Form Values With Hook Form And Hooks

Friends, being a React app developer, we all know that creating a form in React is not a difficult task. The form gathers the information from the user directly. But during creating a form, managing state, from values, validation can prove to be a bit difficult.

 

But since we know that the library called React Hook Form has the hook form module. It keeps the difficulties and complexities at distance. With this, working with forms becomes very simple and swift.

So, in this guide, we will learn how to set form input values in React app using the React Hooks (useEffect and useState) and React Hook form module.

 

There are some easy APIs in React Hook form. We will get to know how to register, handleSubmit and reset APIs to manage the form data easily and dynamically.

 

reset(): This method allows resetting the entire form state or a small part of the form. We will use this API to reset the form values in this React Hook form example.

register(): This method lets us register an input or select element and lay down the foundation of validation rules to React Hook form. All validation rules are based on the HTML standard and support custom validation.

 handleSubmit(): This method obtains the form data if form validation is passed.

 

How To Set/Reset Form Values With Hook Form And React Hooks

Step 1- Create New React Application

Step 2- Install Bootstrap Library

Step 3- Add React Hook Form Package

Step 4- Create Form With Hook Forms

Step 5- Render Form In View

Step 6- Run Development Server

 

Let’s learn in detail now:

Step 1- Create New Application

We will start this tutorial, we simply have to by creating a new React application for which we have to type the command on our terminal’s console and run the command:

npx create-react-app react-proxima

After the app has been installed, we need to move into the project directory:

cd react-proxima

 

Step 2- Install Bootstrap Library

This second step is about creating UI form.

We will add the following command on the console and press enter to start the Bootstrap module installation:

npm install bootstrap

 

Step 3- Add React Hook Form Package

Here, we need to type the given command again on the terminal and execute ti which would install the React Hook form package:

npm install @hookform/resolvers

 

Step 4- Create Form With Hooks Form

So, afterward, we will create a new components/ folder in our project directory. We also have to create the UserForm.js file:

import React, { useState, useEffect } from 'react'
import { useForm } from 'react-hook-form'
export default function UserForm() {
  const { register, handleSubmit, reset } = useForm()
  const [user, inituser] = useState(null)
  useEffect(() => {
    setTimeout(
      () =>
        inituser({
          name: 'Tom Holland',
          email: 'spidy@mcu.com',
          mobile: '202 555 0191',
        }),
      800,
    )
  }, [])
  useEffect(() => {
    reset(user)
  }, [user])
  function onSubmit(dataRes) {
    console.log(dataRes)
    return false
  }
  return (
    <div className="container mt-3">
      <h2>React Set Form Values using React Hook Form Example</h2>
      {user && (
        <form onSubmit={handleSubmit(onSubmit)} className="mt-3">
          <div className="form-group mb-3">
            <label>Name</label>
            <input
              type="text"
              name="name"
              {...register('name')}
              className="form-control"
            />
          </div>
          <div className="form-group mb-3">
            <label>Email</label>
            <input
              type="email"
              name="email"
              {...register('email')}
              className="form-control"
            />
          </div>
          <div className="form-group mb-3">
            <label>mobile</label>
            <input
              type="text"
              name="mobile"
              {...register('mobile')}
              className="form-control"
            />
          </div>
          <div className="d-grid">
            <button type="submit" className="btn btn-primary mb-2">
              Submit
            </button>
            <button
              type="button"
              onClick={() =>
                reset({
                  name: '',
                  email: '',
                  mobile: '',
                })
              }
              className="btn btn-danger"
            >
              Reset
            </button>
          </div>
        </form>
      )}
      {!user && (
        <div className="text-center p-3">
          <span className="spinner-border spinner-border-sm align-center"></span>
        </div>
      )}
    </div>
  )
}

 

Step 5- Render Form In View

Now, we have reached almost the end of this guide. So, we will add and import the user component in App.js file for rendering the user form component in the browser’s view:

import React from 'react'
import UserForm from './components/UserForm.js'
import 'bootstrap/dist/css/bootstrap.min.css'
function App() {
  return (
    <div>
      <UserForm />
    </div>
  )
}
export default App;

 

Step 6- Run Development Server

The last step is just to start the React app which we can do by starting the app development server.

For that, we head over to the console, type the given command and hit enter:

npm start

 

Conclusion

So, we have learned the concepts like form input values and reset form context.

Also, we have seen app creation, package installation, and also component setup. Then, we got to know how to set up the form and multiple form values using hook form in React js app.

We had used useState and useEffect hooks to manage the behavior of the component.

 

Hope that you have found the tutorial quite interesting and easy to implement in your React apps.

 

Good luck!

Leave a Reply

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