gamer gamer - 3 months ago 114
React JSX Question

reactjs event listener beforeunload added but not removed

I have a react component like :

import React, { PropTypes, Component } from 'react'


class MyComponent extends Component {

componentDidMount() {
window.addEventListener("beforeunload", function (event) {
console.log("hellooww")
event.returnValue = "Hellooww"
})
}

componentWillUnmount() {
window.removeEventListener("beforeunload", function (event) {
console.log("hellooww")
event.returnValue = "Hellooww"
})
}

render() {

return (
<div>
Some content
</div>
)
}

}

export default MyComponent


Here event lister is added to the component. When I refresh the page it gives me pop up asking to leave the page.

But when I go to another page and do refresh it again shows the same pop up.

I am removing the
eventListener
from the component on
componentWillUnmount
. Then why it is not being removed

How can I remove the
beoreunload
event on other pages ?

Answer

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:

import React, { PropTypes, Component } from 'react'


class MyComponent extends Component {
    constructor(props) {
        super(props);

        this.onUnload = this.onUnload.bind(this); // if you need to bind callback to this
    }

    onUnload(event) { // the method that will be used for both add and remove event
        console.log("hellooww")
        event.returnValue = "Hellooww"
    }

    componentDidMount() {
       window.addEventListener("beforeunload", this.onUnload)
    }

    componentWillUnmount() {
        window.removeEventListener("beforeunload", this.onUnload)
    }

    render() {

        return (
            <div>
                Some content
            </div>
        )
    }

}

export default MyComponent