・src/components/Pointer.tsx
import { useEffect, useState } from "react";
const Pointer = () => {
const [position, setPosition] = useState({ x: 0, y: 0 });
function handleMove(e) {
setPosition({ x: e.clientX, y: e.clientY });
}
useEffect(() => {
window.addEventListener("pointermove", handleMove);
return () => {
window.removeEventListener("pointermove", handleMove);
};
}, []);
return (
<div
style={{
position: "absolute",
backgroundColor: "blue",
borderRadius: "50%",
opacity: 0.6,
pointerEvents: "none",
transform: `translate(${position.x}px, ${position.y}px)`,
left: -20,
top: -20,
width: 50,
height: 50,
}}
></div>
);
};
export default Pointer;
・This component displays a pointer that follows the movement of the mouse pointer.
・The function of the window object, in this case it is the addEventListener, is one of the side effects.
・The side effects should be used in useEffect, as you can see in this snippet below.
useEffect(() => {
window.addEventListener("pointermove", handleMove);
}, []);
・You should call the cleanup function, which is called when the component is unmounted, to remove eventLisner in this snippet below.
return () => {
window.removeEventListener("pointermove", handleMove);
};
・src/App.tsx
import "./App.css";
import Pointer from "./lessons/Lesson2/Lesson2_1/Pointer";
function App() {
return (
<div className="flex items-center max-w-4xl mx-auto py-8 text-2xl">
<Pointer />
</div>
);
}
export default App;
・This component displays the Pointer componnet.