Reputation: 1500
I am trying to create a keypress listener for my React Js calculator app and when I add the event listener in, it detects additional key presses the more I press. Is there a better place to put the event listener? When I press 1234, I get
122333344444444
/****************Button Component*************/
class CalcApp extends React.Component {
state = {
value: null,
displayNumbers: '0',
selectedNumbers: [],
calculating: false,
operator:null
};
selectMath = (selectedMath) =>{
const {displayNumbers, operator,value} = this.state;
const nextValue = parseFloat(displayNumbers)
console.log(selectedMath);
/**do math and other methods*/
render() {
document.addEventListener('keydown', (event) => {
const keyName = event.key;
if(/^\d+$/.test(keyName)){
this.selectButton(keyName)
console.log(keyName);
}
});
return (
<div>
<Display displayNumbers={this.state.displayNumbers}
selectedNumbers={this.state.selectedNumbers}/>
<Button selectedNumbers={this.state.selectedNumbers}
selectButton ={this.selectButton}
selectC = {this.selectC}
displayNumbers={this.state.displayNumbers}
selectDot = {this.selectDot}
selectMath = {this.selectMath}/>
</div>
);
}
}
let domContainer = document.querySelector('#app');
ReactDOM.render(<CalcApp />, domContainer);
Upvotes: 1
Views: 55
Reputation: 20037
document.addEventListener
listener from render()
.The method is being called whenever the components needs to re-render (changes of state
/ props
) which attaches yet another event listener.
Suggestion: Move document.addEventListener
to componentDidMount()
- executed only once, and remove it via document.removeEventListener
on componentWillUnmount
to prevent memory leaks.
Upvotes: 1