What remove.event.listener do?

Tell us what’s happening:
Describe your issue in detail here.

So, we add event listener which prints text after pressing enter, but i thought that removing this event listener in componentWillUnmount will delete this text after pressing enter again. So, why do we need to use it and what i need to do if i want to remove text after pressing enter again? Thank you for help!

  **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);
}
// 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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 OPR/82.0.4227.50

Challenge: Add Event Listeners

Link to the challenge:

The addEventListener call tells the browser to run your callback function this.handleKeyPress when the user presses a key. removeEventListener tells the browser to stop doing that.

By removing the event listener, you’re telling the browser to stop listening for keydown events, so you won’t know when the user presses a key after removeEventListener is run.

You’d need to modify the callback function this.handleKeyPress to, well, do that.

ok, but after using removeEventListener() browser still typing “you pressed enter key”, nothing stops.

It’s run in the componentWillUnmount hook, but since the component never unmounts while you’re on the page, that code will never be run. (That’s intended)

1 Like

OOOO i understood!!! thank you