'Make hooks stop randomizing background color
So I wanted to use hooks for an exercise where I have a circle follow my cursor in React ( and then see other users circles using node) so I've set a randomColor() function so every page is a different color. However I have no idea how to make it not reroll the color every time I move my cursor.
function randomColor(){
return Math.floor(100000 + Math.random() * 900000)
}
function App() {
const [coord, setCoord] = useState({ x: 0, y: 0 });
const [left, setLeft] = useState({ x: 0});
const [top, setTop] = useState({ y: 0});
const handleMouseMove = (e) => {
setCoord({ x: e.screenX, y: e.screenY });
setTop({ y: e.pageY-50 });
setLeft({ x: e.pageX-10});
let circle = document.getElementById('circle');
circle.style.transform ="translate("+left.x+"px, "+top.y+"px)";
circle.style.top = top + 'px';
console.log("translate("+left.x+"px, "+top.y+"px)")
};
socket.emit("howdy",[left.x,top.y] )
return (
<div style={{ backgroundColor: "#"+randomColor()}}>
<div className="main" onMouseMove={handleMouseMove}>
<h1>
Mouse coordinates: {coord.x} {coord.y} {left.x} {top.y}
</h1>
<div id='circle'></div>
</div>
</div>
)
}
export default App;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|