I am a beginner in React and I have some problems. I want to add some event listeners in componentDidMount() method, plus I need to catch the event to find which key was clicked.
And I want to remove it in componentWillUnmount() method. I did it on with extra function. But there is some issue. After some time passes (for example after one second) I want to update state in parent component(which triggers component unmounting and I did it), but there is One problem I cant remove event listener in componentWillUnmount() so please help me.
here is my code
import React, { Component } from 'react';
class Element extends Component {
componentDidMount(){
const {attributes, startTime, timeOut, automaticAnswer} ={...this.props};
document.addEventListener('keypress', function func(e){
that.handleClick(e, startTime, attributes.keyBoardKey, false, timeOut, func)});
}
handleClick(event, startTime, realAnswer, automaticAnswer, timeOut, func){
this.props.fillAnswer(event.key ? event.key : '', startTime, realAnswer, automaticAnswer, timeOut);
document.removeEventListener('keypress', func);
}
render() {
const {attributes, startTime, timeOut, automaticAnswer} ={...this.props};
if(automaticAnswer ){
this.handleClick('', startTime, attributes.keyBoardKey, true, timeOut);
}
return (
<span className={attributes.className}>{attributes.value}</span>
);
}
}
export default Element;