I can’t rewrite this code into a functional one using the useState and useEffect hooks. The neon cursor should be turned on by the button, but it does not move.
function App() {
const [isCustomCursor, setIsCustomCursor] = React.useState();
function handleChange() {
setIsCustomCursor(!isCustomCursor);
}
return (
<>
<label>
<input type="checkbox" onChange={handleChange}/>
Включить неоновый курсор
</label>
{isCustomCursor && <NeonCursor/>}
</>
);
}
function NeonCursor() {
const [top, setTop] = React.useState(0);
const [left, setLeft] = React.useState(0);
React.useEffect(() => {
function handleMouseMove(event) {
setTop({
top: event.pageY,
});
setLeft({
left: event.pageX,
})
}
document.addEventListener('mousemove', handleMouseMove);
document.documentElement.classList.add('no-cursor');
return () => {
document.documentElement.classList.remove('no-cursor');
document.removeEventListener('mousemove', handleMouseMove);
};
});
return (
<img
src="https://code.s3.yandex.net/web-code/react/cursor.svg"
width={30}
style={{
position: 'absolute',
top: setTop,
left: setLeft,
pointerEvents: 'none',
}}
/>
);
}
ReactDOM.render(<App/>, document.querySelector('#root'));
I hope u can solve my problem. I guess the problem is handleMouseMove function
2
Answers
I got it
useEffect
takes a second argument which should be an empty array in this case. LikeThe empty array means that the hook function runs once when the component is first rendered.