I have read many other stack overflow posts about how bind(this)
creates a new reference for a function, but still I can't get the removeEventHandler
working in react js.
Consider the following example:
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.arr = [1];
this.handeler = this.handeler.bind(this); //stores a new reference
}
handeler(e) {
console.log("click");
e.target.removeEventListener("click", this.handeler); //shouldn't it be the same reference?
e.target.removeEventListener("onclick", this.handeler);
e.target.removeEventListener("onClick", this.handeler);
}
render() {
return (
<div>
<h2>Tesing react inline bind</h2>
{
[1].map(
() => {
return (
<div>
<button onClick={this.handeler} >clickMe</button>
</div>
)
}
)
}
</div>
)
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
There are other SO posts which suggest using useState
or just setting e.target.onClick = null
. I want to understand why doesn't removeEventHandeler
work? Is it something to do with react synthetic events? Also stuff like e.target.onClick = null
doesn't work either.
Other posts, which I refered:
React document.removeEventListener is not working -- in my case re render doesn't happen, I am following react js turorial and haven't got to the chapters of useState, setState or useCallback etc.
https://stackoverflow.com/a/22870717/3429430 -- Yes, I am storing the reference after bind(this) and using the same reference in removeEventListener.