'Cannot Remove Event Listener
Hello i tried to remove the event click event listener from a button.
In my real problem i have multiple scroolbars synced (whenever one changes the other scrolls to the same position) and i want to remove the onscroll event.
I oversimplified the example, but does not work. Any idea?
import { useRef } from "react";
var btnRef;
function clicked(){
alert('btn clicked');
if(btnRef.current){
console.log('remove click listener ...')
btnRef.current.removeEventListener('click', clicked);
}
}
function MyComponent(){
btnRef = useRef();
return (
<button ref={btnRef} onClick={clicked}>click me</button>
);
}
export default MyComponent;
Solution 1:[1]
const [clicked, setClicked] = useState(false);
set clicked to true on button click, add logic to display based on boolean value
Solution 2:[2]
You need to use state and update it when the button is clicked for the first time, so whenever the button is clicked again, do nothing
function MyComponent(){
const [clicked, setClicked] = React.useState(false)
function handleClick(){
if(clicked){
return undefiend
}
setClicked(true)
alert('btn clicked');
}
return (
<button disabled={clicked} onClick={handleClick}>click me</button>
);
}
export default MyComponent;
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 | Sean Lawton |
| Solution 2 | Ahmed Tarek |
