Reactjs event listener beforeunload added but not removed. The removeEventListener should get the reference to the same callback that was assigned in addEventListener. Recreating the function won’t do. The solution is to create the callback elsewhere (onUnload in this example), and pass it as reference to both addEventListener and removeEventListener:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import React, { PropTypes, Component } from 'react'; class MyComponent extends Component { onUnload = e => { // the method that will be used for both add and remove event e.preventDefault(); e.returnValue = ''; } componentDidMount() { window.addEventListener("beforeunload", this.onUnload); } componentWillUnmount() { window.removeEventListener("beforeunload", this.onUnload); } render() { return ( <div> Some content </div> ); } } export default MyComponent |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.