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;
const [clicked, setClicked] = useState(false);
set clicked to true on button click, add logic to display based on boolean value
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;