I'm writing a simple cursor record webpage with Reactjs, the problem is the records array only updates whenever I click the button while my intention for it is to continuously update on mouse move. The logic actually works fine on raw javascript, there's must be something about how react events work that i'm mistaken. The code:
import React, {Component} from 'react';
class MouseRecord extends Component {
constructor(props) {
super(props);
this.state = {
records: [],
displayMessage: false
}
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log(this.state.records);
this.setState(prevState => ({
//records: [],
displayMessage: !prevState.displayMessage
}));
}
handleMouseMove(e) {
e.preventDefault();
if (this.state.records.length <= 100000){
this.setState(prevState => ({
records: prevState.records.concat([{
cor_X: e.clientX,
cor_Y: e.clientY,
width: window.innerWidth,
height: window.innerHeight,
timestamp: new Date().toUTCString()
}])
}));
}
}
componentDidMount() {
document.addEventListener('mousemove', (e) => this.handleMouseMove(e));
}
componentWillUnmount() {
document.removeEventListener('mousemove', (e) => this.handleMouseMove(e));
}
render(){
return(
<div className="box">
<button onClick={this.handleClick}>Click to retrieve mouse records</button>
<div>
{this.state.displayMessage ? this.state.records.length > 0 ? this.state.records.map((record) => {
return (
<div key={this.state.records.indexOf(record)}>
<p>client X: {record.cor_X}</p>
<p>client Y: {record.cor_Y}</p>
<p>Window width: {record.width}</p>
<p>Window height: {record.height}</p>
<p>Timestamp: {record.timestamp}</p>
<br/>
<br/>
</div>
);
}) : null : null}
</div>
</div>
);
}
}
export default MouseRecord;