React - Add Event Listeners

Tell us what’s happening:

I’ve done every possible solution i think I can but still cannot validate
this issue:
Once the component has mounted, pressing enter should update its state and the rendered h1 tag.

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

  componentDidMount() {
    document.addEventListener('keydown', this.handleKeyPress);
  }


  componentWillUnmount() {
    document.removeEventListener('keydown', this.handleKeyPress);

  }
  // Change code above this line
  handleEnter() {
    this.setState((state) => ({
      message: 'You pressed the enter key!'
    }));
  }
  handleKeyPress(event) {
    if(event.key == "Enter"){
      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/134.0.0.0 Safari/537.36

Challenge Information:

React - Add Event Listeners

I just reset this challenge and entered your code passing the test, give it a try.

1 Like

Yeah it did work. The only thing is that instead of copying pasting it I rewrote it .Thanks Bro

1 Like