useMouse
Hook to track mouse position also in relationship with an element. It works with pointerEvents.
Demo
INFO
The component tracks the relative mouse position to element
Loading demo…
Show source code
tsx
import { useRef } from "react";
import { useMouse } from "../../../..";
export const UseMouse = () => {
const ref = useRef<HTMLDivElement>(null);
const { x, y, relativeElementDim: { top = null, left = null, width = null, height = null } = {} } = useMouse({ relativeElement: ref });
return (
<>
<div
ref={ref}
style={{
width: '200px',
height: '200px',
backgroundColor: 'gray',
color: 'white',
lineHeight: '200px',
textAlign: 'center',
}}
>
element
</div>
<div>
<p>
Mouse Position relative to Element - x: {x}, y: {y}
</p>
<p>
Element Dimensions - top: {top} left: {left} width: {width} height: {height}
</p>
</div>
</>
);
}Types
UseMouseOpts
Options for the useMouse.
| Property | Type | Required | Description |
|---|---|---|---|
type | "client" \| "page" \| "screen" | Coordinate space to report pointer positions in. - "client" — relative to the viewport (default). - "page" — relative to the full page (includes scroll offset). - "screen" — relative to the physical screen. | |
relativeElement | RefObject<HTMLElement \| null> \| HTMLElement | When provided, x and y are returned relative to this element's bounding rect rather than the selected coordinate space. The element's DOMRect is also returned as relativeElementDim. |
UseMouseResult
Result object returned by useMouse.
| Property | Type | Required | Description |
|---|---|---|---|
x | number \| null | ✓ | Current horizontal pointer coordinate. null before the first pointer event. |
y | number \| null | ✓ | Current vertical pointer coordinate. null before the first pointer event. |
relativeElementDim | DOMRect | Bounding rect of the relativeElement at the time of the last pointer event. Only present when relativeElement is provided to the hook. |
