Show Loading Spinner after Submit with React Hook Form

    Nov 19, 2021       by Pankaj Kumar

While working with any application, the developer needs to take care of the user-friendliness of the application. The loading spinner is one of the functionalities which is very important to let users know that request is in progress.

In this article, We will see how easily we can add a simple loading spinner after form submit while working with React Hook Form.

Component with React Hook Form Example

 

 
import React from 'react';
import { useForm } from "react-hook-form";
 
function App() {
    const { handleSubmit, formState } = useForm(); // functions imported to build form
    const { isSubmitting } = formState;
 
    function onSubmit(data) {
        // return promise that resolves after 5 seconds
        return new Promise(resolve => {
            setTimeout(() => {
                resolve();
            }, 5000);
        });
    }
 
    return (
      <div className="m-2">
        <h5>Loading Spinner Example with React Hook Form</h5>
        <div>
          <form onSubmit={handleSubmit(onSubmit)}>
             First Name:  <input type="text" /><br/><br/>
              Last Name: <input type="text" /><br/><br/>
            <button disabled={isSubmitting} className="btn btn-primary mr-1">
              {isSubmitting && (
                <span className="spinner-border spinner-border-sm mr-1"></span>
              )}
              Submit
            </button>
          </form>
        </div>
      </div>
    );
}
 
export { App };
 

 

In the above component, we have used Bootstrap for styling, and a promise is used which gets resolved after 5 seconds, which means loader will show over the button for 5 seconds. For small apps, this approach will work but for huge apps where you will make HTTP requests or any state management then the logic will change.

Click here to find more articles on React.

 


WHAT'S NEW

Find other similar Articles here: