Creating a Submit Form with Loading Button in React JS – Code With DS #Button #reactjs #shorts

Posted by






How To Make Submit with Loading Button Using React JS

How To Make Submit with Loading Button Using React JS

In this tutorial, we will learn how to create a submit button with a loading state using React JS. This can be useful when you want to give feedback to the user that their action is being processed.

Step 1: Setting up your React project

If you haven’t already, set up a new React project by running the following command:


npx create-react-app my-app

Replace ‘my-app’ with the name of your project.

Step 2: Creating the SubmitButton component

First, create a new file called SubmitButton.js in your src directory.


import React, { useState } from 'react';

const SubmitButton = () => {
const [isLoading, setIsLoading] = useState(false);

const handleClick = () => {
setIsLoading(true);

// Make your API call or perform your action here
// Once the action is complete, set isLoading back to false
};

return (

);
};

export default SubmitButton;

In this code, we are creating a SubmitButton component that uses the useState hook to track the loading state. When the button is clicked, the handleClick function is called which sets isLoading to true. The button’s text is then updated to ‘Loading…’. Once the action is complete, isLoading is set back to false and the button’s text is updated to ‘Submit’.

Step 3: Using the SubmitButton component

Now that we have created the SubmitButton component, we can use it in our app. Open App.js and import the SubmitButton component. Then, use the component in the return statement:


import React from 'react';
import './App.css';
import SubmitButton from './SubmitButton';

function App() {
return (

My React App

);
}

export default App;

Step 4: Testing the SubmitButton

Start your React app by running the following command:


npm start

Now, when you click the ‘Submit’ button, it should change to ‘Loading…’ and then back to ‘Submit’ once the action is complete.

Conclusion

Congratulations! You have successfully created a submit button with a loading state using React JS. This can greatly improve the user experience by providing feedback during long-running actions.