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) {
    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() {
      message: this.state.message + 'You pressed the enter key! '
  handleKeyPress(event) {
    if (event.keyCode === 13) {
  render() {
    return (

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:

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 about removeEventListener(), it’s useful stuff. :wink: