I currently have a react component and I am trying to have a windows event listener that triggers on each keydown and will react if it is the tab key, but currently it is hitting multiple times each time
Is there anyway to make it so each keydown is trigger once only? Here is the code
render() {
window.addEventListener('keydown',(event) => {
// here the eventListener should only trigger once per keypress, but it's hitting 4 times
console.log("event",event);
})
}
addEventListener does not belong into the render() function.
There it will create a new event listener on every rerender of that component.
Instead, put it into componentDidMount lifecycle hook.
class Component extends React.Component{
handleKeyDown =(event) =>{
// here the eventListener should only trigger once per keypress, but it's hitting 4 times
console.log("event",event);
}
componentDidMount(){
window.addEventListener('keydown',this.handleKeyDown)
}
componentWillUnmount(){
window.removeEventListener('keydown',this.handleKeyDown)
}
render() {
return <button onClick={()=>this.setState((state)=>({test:state?.test+1}))}>test</button>
}
}
Keep in mind, setting an event listener on window will create a global event listener. You should remove it, when you don't need it anymore, e.g. on componentWillUnmount