Adding-Event-Listeners(Reactjs)

Tell us what’s happening:
hello, I want to understand what this code is doing and is there any way I can put for example console.log() to see the output on the browser.
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((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 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.58 Safari/537.36

Challenge: Add Event Listeners

Link to the challenge:

In this code an event listener is attached to keydown event. Means every time you press a key in keyboard a function will be triggered. Here handleKeyPress is the function .

The handleKeyPress function will check which key is pressed. If the keycode equal to 13 (enter key) another function called handleEnter will be triggered.

The handleEnter function will set your state message to 'You pressed the enter key! ’

1 Like

You can simply add a console.log to your handler, and it will be called when the handler is. The handlers output will be generally undefined as they are not used to return values.

handleEnter() {
    console.log('handleEnter triggered')
    this.setState((state) => ({
      message: state.message + 'You pressed the enter key! '
    }));
  }

  handleKeyPress(event) {
    console.log('handleKeyPress triggered')
    if (event.keyCode === 13) {
      this.handleEnter();
    }
  }

You need to actually click on the white screen and then click enter as that is what the document listener is attached to.

1 Like

thank you @adramelech for this explanation, I see it more clearly. do you have an links to articles or publications for further reading.

thank you @caryaharper. I had trouble in trying to find where to put console log to understand what I was coding. trying it out it makes sense now.

WDS

Check this video for understand more about event listeners

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.