Skip to content

Instantly share code, notes, and snippets.

@mirosh-kavinda
Last active October 31, 2022 17:36
Show Gist options
  • Save mirosh-kavinda/f0f72c6d786bbaa99c8db2711d6a9132 to your computer and use it in GitHub Desktop.
Save mirosh-kavinda/f0f72c6d786bbaa99c8db2711d6a9132 to your computer and use it in GitHub Desktop.
Create Cursor for your react app

#use Pure CSS and useEFfect to generate mouse cursor on your react App

cursor

#Insert the DotRing component to the App Component in the react app File hierarchy you need to put files on :

  src
      components
      ------DotRing
            ------DotRing.js
            ------DotRing.css
      hook
      -------useMousePosition.js
      App.js
import DotRing from "./components/DotRing/index";
export default function App() {
return (
<div class="App">
<DotRing />
....
</div>
);
}
.ring {
position: fixed;
top: 0;
left: 0;
width: 22px;
height: 22px;
border: 2px solid rgba(255, 255, 255, 0.808);
border-radius: 100%;
transform: translate(-50%, -50%);
-webkit-transition-duration: 100ms;
transition-duration: 100ms;
-webkit-transition-timing-function: ease-out;
transition-timing-function: ease-out;
will-change: width, height, transform, border;
z-index: 999;
pointer-events: none;
}
.dot {
position: fixed;
top: 50%;
left: 50%;
width: 8px;
height: 8px;
background-color: rgb(255, 255, 255);
border-radius: 100%;
transform: translate(-50%, -50%);
z-index: 999;
pointer-events: none;
}
import "./DotRing.css";
import useMousePosition from "../../hooks/useMousePosition";
const DotRing = () => {
// 1.
const { x, y } = useMousePosition();
return (
<>
{/* 2. */}
<div
style={{ left: `${x}px`, top: `${y}px` }}
className="ring"
></div>
{/* 3. */}
<div
className="dot"
style={{ left: `${x}px`, top: `${y}px` }}
></div>
</>
);
};
export default DotRing;
import { useEffect, useState } from "react";
export default function useMousePosition() {
const [mousePosition, setMousePosition] = useState({ x: null, y: null });
useEffect(() => {
const mouseMoveHandler = (event) => {
const { clientX, clientY } = event;
setMousePosition({ x: clientX, y: clientY });
};
document.addEventListener("mousemove", mouseMoveHandler);
return () => {
document.removeEventListener("mousemove", mouseMoveHandler);
};
}, []);
return mousePosition;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment