Hello Everyone,
so my question is actually what is the difference here IF we do not write the componentWillUnmount() method.
I like to test everything to make sure I know what each thing is being used for but in this case if i press Enter with the componentWillUnmount() method I have the same result as if I had pressed it without the componentWillUnmount() in the code.
Could someone explain to me what it is doing here?
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
message: ''
};
this.handleEnter = this.handleEnter.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
}
// Change code below this line
componentDidMount() {
document.addEventListener("keydown",this.handleKeyPress)
}
componentWillUnmount() {
document.removeEventListener("keydown", this.handleKeyPress)
}
// Change code above this line
handleEnter() {
this.setState((state) => ({
message: state.message + 'You pressed the enter key! '
}));
}
handleKeyPress(event) {
if (event.keyCode === 13) {
this.handleEnter();
}
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
</div>
);
}
};
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36
.
Challenge: Add Event Listeners
Link to the challenge: