Skip to main content

useMouse

A hook that tracks mouse position relative to a target element.

It provides the position on the user's screen, within the viewport, within the full document, relative to the target element, and the element's own position.

If no target element is assigned, the element-relative position and element position values will not be provided.


Code

🔗 View source code


Interface

typescript
interface CursorPosition {
screenX: number | null;
screenY: number | null;
clientX: number | null;
clientY: number | null;
pageX: number | null;
pageY: number | null;
elementRelativeX: number | null;
elementRelativeY: number | null;
elementPositionX: number | null;
elementPositionY: number | null;
}

function useMouse<T extends HTMLElement>(): {
ref: React.RefObject<T | null>;
position: CursorPosition;
}

Returns

NameTypeDescription
refReact.RefObject<T | null>Ref to attach to the target element for mouse tracking
positionCursorPositionObject containing the current mouse position data
position.screenXnumber | nullX coordinate within the user's monitor
position.screenYnumber | nullY coordinate within the user's monitor
position.clientXnumber | nullX coordinate within the viewport
position.clientYnumber | nullY coordinate within the viewport
position.pageXnumber | nullX coordinate relative to the full document
position.pageYnumber | nullY coordinate relative to the full document
position.elementRelativeXnumber | nullX coordinate relative to the target element (null if no element)
position.elementRelativeYnumber | nullY coordinate relative to the target element (null if no element)
position.elementPositionXnumber | nullX coordinate of the target element (null if no element)
position.elementPositionYnumber | nullY coordinate of the target element (null if no element)

Usage

typescript
import { useMouse } from '@modern-kit/react';

const Example = () => {
const { ref, position } = useMouse<HTMLDivElement>();
const boxStyle = useMemo(() => {
return {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: '500px',
height: '500px',
background: '#439966',
fontSize: '2rem',
color: '#fff',
}
}, []);

return (
<>
<div ref={ref} style={boxStyle}>
Move your mouse here.
</div>
<p>Screen X: {position.screenX}</p>
<p>Screen Y: {position.screenY}</p>
<p>Client X: {position.clientX}</p>
<p>Client Y: {position.clientY}</p>
<p>Page X: {position.pageX}</p>
<p>Page Y: {position.pageY}</p>
<p>Element Relative X: {position.elementRelativeX}</p>
<p>Element Relative Y: {position.elementRelativeY}</p>
<p>Element Position X: {position.elementPositionX}</p>
<p>Element Position Y: {position.elementPositionY}</p>
</>
);
};

Example