Last updated: Apr 6, 2024
Reading time·2 min
To prevent multiple button clicks in React:
onClick
prop on the button, passing it a function.disabled
attribute to true
.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
.
The currentTarget
property on the event gives us access to 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.
ref
This is a three-step process:
ref
prop on the button element.current.disabled
property to
true
.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;
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.
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.
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.
If you need to change a button's text on click, check out the following article.