DEV Community

Randy Rivera
Randy Rivera

Posted on

React: Add Event Listeners

  • FreeCodeCamp says that the componentDidMount() method is also the best place to attach any event listeners you need to add for specific functionality. In which React provides a synthetic event system which wraps the native event system present in browsers.
  • We've already been using some of these synthetic event handlers such as onClick(). But, if you want to attach an event handler to the document or window objects, you have to do this directly.

  • Today we have to add an event listener in the componentDidMount() method for keydown events and have these events trigger the callback handleKeyPress(). We can use the document.addEventListener() which takes the vent (in quotes) as the first argument and the callback as the second argument.

  • After that , in componentWllMount(), remove the same event listener with doucment.removeEventListener().

  • Code:

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() {

  }
  componentWillUnmount() {

  }
  // 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>
    );
  }
};
Enter fullscreen mode Exit fullscreen mode
  • Answer:
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      message: ''
    };
    this.handleEnter = this.handleEnter.bind(this);
    this.handleKeyPress = this.handleKeyPress.bind(this);
  }
  componentDidMount() {
   document.addEventListener("keydown", this.handleKeyPress)

  }
  componentWillUnmount() {
    document.removeEventListener("keydown", this.handleKeyPress)

  }
  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>
    );
  }
};
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
georgewl profile image
George WL • Edited

any example for Functional components? they're much preferred since React update 16.x.x which released four years ago