Add Event s help me in this

Tell us what’s happening:
can u tell what is componentWillUnmount() is doing here

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.addEventListener("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/75.0.3770.142 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/react/add-event-listeners

Then, in componentWillUnmount() , remove this same event listener. You can pass the same arguments to document.removeEventListener()

You are using document.addEventListener() in the componentWillUnmount().

1 Like

componentWillUnmount() is called when the React component is being kicked out of memory. So, for example, if you have a React app that the user can log out of, when they log out, you might unmount the app. Or when the page is closed.

What you are being asked to do is removeEventListener() in the unmount cycle, as at that point, you can free up that portion of memory. If the component is no longer mounted, for whatever reason, it is good form for it to stop listening for stuff.

As @Tchoukoualeu has said, though, you are doing document.addEventListener() in the componentWillUnmount(), rather than document.removeEventListener(). And I do recommend reading the bit on https://devdocs.io/ about removeEventListener(), it’s useful stuff. :wink: