In this article, we will see how to prevent the user from clicking the button again and again until the required action is completed.
By using the state variable, we can keep track of whether the button is clicked or not. When the button is clicked, the state variable is set to true and the button is disabled. This prevents the user from clicking the button again and again.
Following is the example of how to implement this:
import React, { useState } from 'react';
function MyButton() {
const [clicked, setClicked] = useState(false);
const handleClick = () => {
if (!clicked) {
setClicked(true);
// perform intended action here
}
};
return (
<button onClick={handleClick} disabled={clicked}>
{clicked ? 'Processing...' : 'Click me'}
</button>
);
}
In the above example, we define a state variable clicked
using the useState
hook.
The handleClick
function checks if the button has already been clicked or not.
If the button is not already clicked, sets the state variable to true and performs the intended action.
The value of clicked
is set to disabled
prop, which prevents the user from clicking the button again and again.
Once, the process is completed, enable the button by setting the clicked
to false.