Categories
React Answers

How to Prevent Multiple Button Presses with React?

Spread the love

Sometimes, we want to prevent multiple button presses with React.

In this article, we’ll look at how to prevent multiple button presses with React.

Prevent Multiple Button Presses with React

To prevent multiple button presses with React, we can set the disabled prop to true when the button is clicked.

For instance, we can write:

import { useState } from "react";

export default function App() {
  const [disabled, setDisabled] = useState(false);
  return (
    <button
      disabled={disabled}
      onClick={() => {
        setDisabled(true);
      }}
    >
      click me
    </button>
  );
}

to add the disabled state with the useState hook.

We set the initial value of the state to false .

Then we set the disabled prop of the button to the disabled state.

Next, we set the onClick prop to a function that calls setDisabled with true to set disabled to true .

And when it’s true , the button is disabled since disabled prop has disabled state as its value.

Conclusion

To prevent multiple button presses with React, we can set the disabled prop to true when the button is clicked.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

2 replies on “How to Prevent Multiple Button Presses with React?”

this solution doesn’t work because useState is an asynchronous system so before disabled will be true, you can click rapidly on the button

Leave a Reply

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