Last active
February 19, 2024 08:54
-
-
Save hypersnob/ad1a71ef5182386acf31333ee2889563 to your computer and use it in GitHub Desktop.
Custom cursor wrapper react component using Framer Motion and Tailwind CSS classes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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