useMouse

useMouse (마우스 좌표)

useMouse 훅은 대상 요소(또는 document)에 대한 마우스 좌표를 추적해요. ref와 x, y 좌표를 반환해요.

출처: 문서

본문

useMouse 훅을 사용해 요소에 대한 마우스 좌표를 추적할 수 있어요.

import { Text, Code, Group, Box } from '@mantine/core';
import { useMouse } from '@mantine/hooks';

function Demo() {
  const { ref, x, y } = useMouse();

  return (
    <Box
      ref={ref}
      style={{
        width: 400,
        height: 200,
        border: '1px solid',
        borderColor: 'var(--mantine-color-gray-3)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <Code>
        Mouse coordinates {`{ x: ${x}, y: ${y} }`}
      </Code>
    </Box>
  );
}

ref를 제공하지 않으면 마우스 위치는 document 요소를 기준으로 추적돼요.

import { Text, Code } from '@mantine/core';
import { useMousePosition } from '@mantine/hooks';

function Demo() {
  const { x, y } = useMousePosition();

  return (
    <Code>
      Mouse coordinates {`{ x: ${x}, y: ${y} }`}
    </Code>
  );
}

API

resetOnExit 옵션을 설정하면 마우스가 요소를 벗어날 때 마우스 위치를 0, 0으로 재설정해요.

import { useMouse } from '@mantine/hooks';

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

훅은 ref와 x, y 마우스 좌표를 가진 객체를 반환해요.

import { useMouse } from '@mantine/hooks';

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();

첫 번째 렌더링(SSR 포함)에서는 x와 y 값이 모두 0이에요.

정의 (Definition)

function useMouse(options?: {
  resetOnExit?: boolean;
}): {
  x: number;
  y: number;
  ref: React.RefObject;
};

더 알아보기 (Learn more)