use-mouse

Get mouse position relative to viewport or given element
Import

Usage

Mouse coordinates { x: 0, y: 0 }
import { Text, Code, Group, Box } from '@mantine/core';
import { useMouse } from '@mantine/hooks';
function Demo() {
const { ref, x, y } = useMouse();
return (
<>
<Group position="center">
<Box
ref={ref}
w={300}
h={180}
sx={(theme) => ({
backgroundColor:
theme.colorScheme === 'dark' ? theme.colors.dark[5] : theme.colors.gray[1],
})}
/>
</Group>
<Text align="center">
Mouse coordinates <Code>{`{ x: ${x}, y: ${y} }`}</Code>
</Text>
</>
);
}

If you do not provide ref mouse position will be captured relative to document element:

Mouse coordinates { x: 0, y: 0 }
import { Text, Code } from '@mantine/core';
import { useMouse } from '@mantine/hooks';
function Demo() {
const { x, y } = useMouse();
return (
<Text align="center">
Mouse coordinates <Code>{`{ x: ${x}, y: ${y} }`}</Code>
</Text>
);
}

API

Set resetOnExit option to reset mouse position to 0, 0 when mouse leaves the element

const { ref, x, y } = useMouse({ resetOnExit: true });

Hook returns object with ref and x, y mouse coordinates:

const {
ref, // -> pass ref to target element, if not used document element will be used as target element
x, // -> mouse x position
y, // -> mouse y position
} = useMouse();

On the first render (as well as during SSR), both x and y values are equal to 0.

Definition

function useMouse<T extends HTMLElement = any>(options?: {
resetOnExit?: boolean;
}): {
x: number;
y: number;
ref: React.MutableRefObject<T>;
};