0

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.

user31782
  • 7,087
  • 14
  • 68
  • 143
  • "*Is it something to do with react synthetic events?*" - yes, quite certainly. Notice that on every re-render of the component, react would add the event listener back anyway - if you need to dynamically add/remove the listener, you should use state in your component and conditionally create the `onclick` prop on the jsx element. – Bergi Oct 04 '22 at 02:58
  • 3
    In short, you did all the `.bind()` stuff correctly, but `removeEventListener` only works when you used `addEventListener` yourself. – Bergi Oct 04 '22 at 02:59
  • @Bergi thanks for explaining. In my actual project, I actually do need to have the `onClick` work after a rerender. For the `removeEventListener` stuff, how does react actually attach event handlers internally then? – user31782 Oct 04 '22 at 03:40

0 Answers0