Tell us what’s happening:
I answered the challenge correctly but i have a couple of questions :
1- can someone tell me what i should write if i wanted a fixed sentence like " u pressed on the keyboard" to appear on the browser when the user presses any key not just the enter key which has a keycode of 13 ?
handleKeyPress(event) {
if (event.keyCode === 13) {
this.handleEnter();
}
}
2-when is a component unmounted ?..in this example so far the component did not unmount at any time and the result (with the current syntax ) produces the same result without the componentWillUnmount method
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.handleEnter();
}
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
</div>
);
}
};
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/react/add-event-listeners