Docs
useMousePosition

Use the useCopyToClipboard hook to copy text to the clipboard and track whether the copy action was successful, with an optional delay to reset the copied state.

Use a ref to add coords relative to the element

Installation

pnpm dlx shadcn@latest add https://hookcn.ouassim.tech/r/use-mouse-position

Usage

"use client"
 
import React from "react"
 
import { useMousePosition } from "@/hooks/useMousePosition"
 
export default function App() {
  const [position, ref] = useMousePosition<HTMLDivElement>()
 
  return (
    <div>
      <div
        ref={ref}
        style={{
          width: "300px",
          height: "300px",
          background: "lightgray",
          position: "relative",
        }}
      >
        <p>
          Mouse position inside element: {position.elementX},{" "}
          {position.elementY}
        </p>
      </div>
      <p>
        Mouse position in viewport: {position.x}, {position.y}
      </p>
    </div>
  )
}

API Reference

Returns

The useMousePosition hook returns an array with two elements:

NameTypeDescription
statePositionTracks mouse position relative to the viewport and an optional element.
refReact.Ref<T>A ref to attach to a DOM element for relative position tracking.

The state object (of type Position) has the following properties:

NameTypeDescription
xnumberHorizontal position in the viewport.
ynumberVertical position in the viewport.
elementX?numberHorizontal position relative to the referenced element.
elementY?numberVertical position relative to the referenced element.
elementPositionX?numberReferenced element’s horizontal position in the document.
elementPositionY?numberReferenced element’s vertical position in the document.