Skip to content

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.

PropertyTypeRequiredDescription
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.
relativeElementRefObject<HTMLElement \| null> \| HTMLElementWhen 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.

PropertyTypeRequiredDescription
xnumber \| nullCurrent horizontal pointer coordinate. null before the first pointer event.
ynumber \| nullCurrent vertical pointer coordinate. null before the first pointer event.
relativeElementDimDOMRectBounding rect of the relativeElement at the time of the last pointer event. Only present when relativeElement is provided to the hook.

Released under the MIT License.