I have some react component and needed to work with "Enter" function.
class MyComponent extends Component {
componentDidMount() {
console.log('componentDidMount');
document.removeEventListener('keypress', this.enter);
document.addEventListener('keypress', this.enter.bind(this));
}
componentWillUnmount() {
console.log('componentWillUnmount');
document.removeEventListener('keypress', this.enter);
}
render() {
return (...);
}
enter(target) {
if (target.charCode === 13) {
console.log('fired');
/* after that component unmounted */
}
}
}
Console log show:
componentDidMount
fired
componentWillUnmount
, but when press Enter the console show again fired
.
this.enter.bind(this)
returns a new function, which is not the same function asthis.enter
. So yourremoveEventListener
is ignored, because that specific function isn't on the event list.Remember the result of
this.enter.bind(this)
and use that when removing.(There's also no need for your
removeEventListener
incomponentDidMount
.)Since you're using ES2015+ syntax, I'll assume you're transpiling. If you are, you could use an arrow function rather than a method for
enter
:That requires that you enable handling of class properties in your transpiler (in Babel, they're currently part of the
stage-2
preset).