React - Add Event Listeners

Tell us what’s happening:
Describe your issue in detail here.

“if you want to attach an event handler to the document or window objects, you have to do this directly”
what does that mean? can you elaborate or send me an article that talks more about that?

what is the difference between onClick and document.addEventListener() ?
when to use which?

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:106.0) Gecko/20100101 Firefox/106.0

Challenge: React - Add Event Listeners

Link to the challenge:

Also… does that mean you can use onClick for html elements in react, but if you want to attach an event listener to the window or document object, you cannot use onClick and have to use document.addEventListener?

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