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!
@Summerflowerling Hmmm I believe there’s nothing wrong with your solution. I guess maybe in the tutorial, they are using handlerEnter()
because it is cleaner.
In the future, you might have something like the below
handleKeyPress(event) {
if (event.keyCode === 13) {
handleEnter();
return;
}
if(event.keyCode === 27 ) { //escape keyCode is 27
handleEsc();
return;
}
}
Nonetheless, I don’t think there’s anything wrong with your simplification 
1 Like
What if you wanted to do something different if another key was pressed? Maybe if the user pressed the space bar on the keyboard, you want to display a message and change the color of the background? Your handleKeyPress method would be the main method to handle all key presses and would call the applicable method (i.e handleEnter, handleSpacebar, etc.) depending on what key was pressed.
1 Like
Much like others have said above, it’s about the architecture, rather than just functioning.
The above examples demonstrate leaving your code open to extension. You can easily add new features as requirements change (eg a new button press to handle).
You can also think about it in terms of separation of concerns.
handleKeyPress
interprets a user input and dispatches an appropriate handler.
handleEnter
executes some behavior. It’s behavior in this case isn’t strictly about the enter key, in my opinion, so I may not have chosen that name. It sets the state to a particular string.
The important point is that they do different things. Separating them makes it easier to reason about them individually, and easier to test them individually.
1 Like