- FreeCodeCamp says that the
componentDidMount()
method is also the best place to attach any event listeners you need to add for specific functionality. In which React provides a synthetic event system which wraps the native event system present in browsers. We've already been using some of these synthetic event handlers such as
onClick()
. But, if you want to attach an event handler to the document or window objects, you have to do this directly.Today we have to add an event listener in the
componentDidMount()
method forkeydown
events and have these events trigger the callbackhandleKeyPress()
. We can use thedocument.addEventListener()
which takes the vent (in quotes) as the first argument and the callback as the second argument.After that , in
componentWllMount()
, remove the same event listener withdoucment.removeEventListener()
.Code:
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>
);
}
};
- Answer:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
message: ''
};
this.handleEnter = this.handleEnter.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
}
componentDidMount() {
document.addEventListener("keydown", this.handleKeyPress)
}
componentWillUnmount() {
document.removeEventListener("keydown", this.handleKeyPress)
}
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>
);
}
};
Top comments (1)
any example for Functional components? they're much preferred since React update 16.x.x which released four years ago