Prevent multiple Button clicks in React

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Ali Pazani

Prevent multiple Button clicks in React #

To prevent multiple button clicks in React:

  1. Set an onClick prop on the button, passing it a function.
  2. When the button gets clicked, set its disabled attribute to true.
App.js
const App = () => { const handleClick = event => { event.currentTarget.disabled = true; console.log('button clicked'); }; return ( <div> <button onClick={handleClick}>Click</button> </div> ); }; export default App;

We set an onClick prop on the button element. When the button gets clicked, the handleClick function is invoked.

We used the currentTarget property on the event to get a reference to the button and set its disabled attribute to true.

react prevent multiple button clicks

The currentTarget property on the event gives us access the element that the event listener is attached to.

Whereas the target property on the event gives us a reference to the element that triggered the event (could be a descendant).

Alternatively, you can use a ref to prevent multiple button clicks in React.

App.js
import {useRef} from 'react'; const App = () => { const buttonRef = useRef(null); const handleClick = event => { buttonRef.current.disabled = true; console.log('button clicked'); }; const handleReset = event => { buttonRef.current.disabled = false; }; return ( <div> <button ref={buttonRef} onClick={handleClick}> Click </button> <hr /> <button onClick={handleReset}>Reset</button> </div> ); }; export default App;

react prevent multiple button clicks ref

The useRef() hook can be passed an initial value as an argument. The hook returns a mutable ref object whose .current property is initialized to the passed argument.

Notice that we have to access the current property on the ref object to get access to the button element on which we set the ref prop.

When we pass a ref prop to an element, e.g. <button ref={myRef}>, React sets the .current property of the ref object to the corresponding DOM node.

The useRef hook creates a plain JavaScript object, but gives you the same ref object on every render. In other words, it's pretty much a memoized object value with a .current property.

Now we can directly reference the button and set its disabled property via buttonRef.current.disabled.

You should use this approach if you need to enable the button later on in your code.

Use the search field on my Home Page to filter through my more than 1,000 articles.