How to prevent multiple button presses with React?

Estimated read time 2 min read

To prevent multiple button presses with React, you can disable the button after it has been clicked using state. This will prevent the user from clicking the button multiple times before the action has completed.

Here’s an example code snippet that demonstrates how to prevent multiple button presses with React:

import React, { useState } from 'react';

function MyButton() {
  const [isLoading, setIsLoading] = useState(false);

  const handleClick = async () => {
    setIsLoading(true);
    try {
      // Perform async action here
      await fetch('https://jsonplaceholder.typicode.com/posts');
    } catch (error) {
      console.log(error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <button onClick={handleClick} disabled={isLoading}>
      {isLoading ? 'Loading...' : 'Submit'}
    </button>
  );
}

export default MyButton;

In this example, we define a functional component named “MyButton” that includes a button that triggers an async action when clicked. We use the useState hook to create a state variable for the loading state.

We define a function named handleClick that is called when the button is clicked. This function sets the loading state to true, performs the async action (in this case, a fetch request to a dummy API), and sets the loading state back to false when the action has completed.

In the JSX code, we bind the onClick event to the handleClick function and disable the button when the loading state is true. This will prevent the user from clicking the button multiple times before the action has completed.

By disabling the button after it has been clicked, we can ensure that the action is only triggered once and prevent any potential issues that may arise from multiple button presses.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply