use-mouse

Get mouse position relative to viewport or given element
Import

Usage

Provide ref to track mouse position over any element:

Mouse coordinates { x: 0, y: 0 }
import { useMantineTheme, Text, Code, Group } from '@mantine/core';
import { useMouse } from '@mantine/hooks';
function Demo() {
const theme = useMantineTheme();
const { ref, x, y } = useMouse();
return (
<>
<Group position="center">
<div
ref={ref}
style={{
width: 300,
height: 180,
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 { useMantineTheme, Text, Code } from '@mantine/core';
import { useMouse } from '@mantine/hooks';
function Demo() {
const theme = useMantineTheme();
const { x, y } = useMouse();
return (
<Text align="center">
Mouse coordinates <Code>{`{ x: ${x}, y: ${y} }`}</Code>
</Text>
);
}

API

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>(): {
x: number;
y: number;
ref: React.MutableRefObject<T>;
};
Build fully functional accessible web applications faster than ever
Feedback
Your feedback is most valuable contribution to the project, please share how you use Mantine, what features are missing and what is done good
Leave feedback