Tell us what’s happening:
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({
message: this.state.message + 'You pressed the enter key! '
});
} */
handleKeyPress(event) {
if (event.keyCode === 13) {
this.setState({
message: this.state.message + 'You pressed the enter key! '
});
}
}
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/77.0.3865.120 Safari/537.36
.
Challenge: Add Event Listeners
Link to the challenge:
https://www.freecodecamp.org/learn/front-end-libraries/react/add-event-listeners
My question is why do we need handleEnter()
here?
I tried to set state within handleKeyPress(event)
and it still works, so I am curious about the difference.
Thanks!