'I have a button in my react app that i only want it to be pressed once
I have implemented this onclick event in it and I want the functions inside the onclick event to run once
<button className='btn2' onClick={() => {
OpenForm();
if (IsLoggedIn === true){
Like();
}else if(IsLoggedIn === false){
return;
}
}}>
Solution 1:[1]
What you need to do is keep track of that using state, let's say a hasClicked, the default state will be false and you changed that in the onClick handler you have up there, an example code snippet would be like:
import { useState } from 'react'
const MyComponent = () => {
const [hasClicked, setHasClicked] = useState(false)
...
const btnClickHandler = () => {
...
setHasClicked(true)
...
}
return (
<button disabled={hasClicked} onClick={btnClickHandler}>Click<button/>
)
}
That way, the button will be disabled once the user clicks on it because disabled will now be pointing to a true hasClicked value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | usmahm |
