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;
}
}}>
CodePudding user response:
If you want users to be able to press the button only once and then disable it after it was pressed, you can try this:
import { useState } from 'react'
function MyComponent() {
const [disabled, setDisabled] = useState(false);
const handleClick = () => {
IsLoggedIn && Like();
IsLoggedIn && setDisabled(true);
};
return (
<>
...
<button disabled={disabled} onClick={handleClick}>Click me</button>
...
</>
}
CodePudding user response:
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.