freeCodeCamp Challenge Guide: Add Event Listeners - Guide - The freeCodeCamp Forum

PHOTO EMBED

Mon Dec 12 2022 10:33:43 GMT+0000 (Coordinated Universal Time)

Saved by @abdishakur #react.js

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>
    );
  }
}
content_copyCOPY

https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-add-event-listeners/301377