JP-Dub
June 20, 2018, 2:53pm
1
Tell us what’s happening:
what’s wrong in my code?
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', handleKeyPress);
}
componentWillUnmount() {
document.removeEventListener('keydown', 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.handleEnter();
}
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
</div>
);
}
};
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/react/add-event-listeners
Hi, my error is ‘handleKeyPress is not defined’. If I understand correctly the callback is failing - though not sure why. Any help is greatly appreciated. Also, I have tried to write out the code like so for both add and remove, below is an example:
document.addEventListener(‘keydown’, function() {
handleKeyPress();
});
the error is saying that no event listener is attached
1 Like
Hi @JP-Dub
When inside a class method and referring to other methods/properties in the class, you need to use the this
keyword.
// Your's
document.addEventListener('keydown', handleKeyPress);
// What it should be
document.addEventListener('keydown', this.handleKeyPress);
13 Likes
JP-Dub
June 20, 2018, 3:04pm
3
Hi,
Thank you! I had tried using ‘this’ before the document and in place of document, believing ‘this’ was involved. It never occurred to me to use it in the callback. Again, thank you.
2 Likes