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.
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
The async code finishes running before most people can do the second click.