Skip to content

Instantly share code, notes, and snippets.

@hypersnob
Last active February 19, 2024 08:54
Show Gist options
  • Save hypersnob/ad1a71ef5182386acf31333ee2889563 to your computer and use it in GitHub Desktop.
Save hypersnob/ad1a71ef5182386acf31333ee2889563 to your computer and use it in GitHub Desktop.
Custom cursor wrapper react component using Framer Motion and Tailwind CSS classes.
import { m } from "framer-motion";
import React, { useEffect, useState } from "react";
const CustomCursor: React.FC<{ cursorElement: JSX.Element }> = ({
cursorElement,
}) => {
const [mousePosition, setMousePosition] = useState({ x: -100, y: -100 });
const onMouseMove = (e: MouseEvent) => {
if (!e.target) {
return;
}
const newX = e.clientX;
const newY = e.clientY;
setMousePosition({ x: newX, y: newY });
};
useEffect(() => {
const body = document.querySelector("body");
if (!body) {
return;
}
body.addEventListener("mousemove", onMouseMove);
body.classList.add("cursor-none");
return () => {
body.removeEventListener("mousemove", onMouseMove);
body.classList.remove("cursor-none");
};
}, []);
return (
<m.div
className="fixed pointer-events-none"
style={{
left: mousePosition.x,
top: mousePosition.y,
zIndex: 1000,
}}
>
{cursorElement}
</m.div>
);
};
export default CustomCursor;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment