componentWillUnmount()
This method is called before a component is unmounted from the DOM.
It is a good place to perform cleaning operations like:
componentWillUnmount(){
...
}
An example of removing attached event listener in componentWillUnMount
import React, { Component } from 'react';
export default class SideMenu extends Component {
constructor(props) {
super(props);
this.state = {
...
};
this.openMenu = this.openMenu.bind(this);
this.closeMenu = this.closeMenu.bind(this);
}
componentDidMount() {
document.addEventListener("click", this.closeMenu);
}
componentWillUnmount() {
document.removeEventListener("click", this.closeMenu);
}
openMenu() {
...
}
closeMenu() {
...
}
render() {
return (
<div>
<a
href = "javascript:void(0)"
className = "closebtn"
onClick = {this.closeMenu}
>
×
</a>
<div>
Some other structure
</div>
</div>
);
}
}