How do I remove an EventListener?

Tell us what’s happening:

Hello.
My code succeeds at passing the lesson.
However, after pressing Enter, shouldn’t the eventListener be removed?

If I press Enter again, the text " You pressed the enter key!" gets appended.

Your code so far


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, true)

}
// change code above this line
handleEnter() {
  this.setState({
    message: this.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; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0.

Challenge: Add Event Listeners

Link to the challenge:

Hello there.

This all depends on your use case. The lesson assumes, whilst your component exists (has been mounted on the page), have the event listener listening for a keydown event. Once the component is removed from the page, remove the event listener.

So, this method would not work for a one-time keydown event. For that, I think the most reliable approach would be the useEffect hook.

Hope this helps

Ah ok.
So it’s a part of a future lesson or not covered right now or for something that is temporary.

My solution is Ok then?
There’s nothing else I could do at the moment, right?

What you did is what was expected.

If you are interested, the official documentation is well formatted:

  1. componentWillUnmount
  2. useEffect

Honestly, everything comes together so well in React, once you start a project written in it. The biggest issue I have had is all the transitioning between class components and functional components.

Hope this helps