useMove

useMove (이동·드래그 감지)

useMove 훅은 사용자가 요소 위에서 누른 마우스를 움직일 때 0에서 1 사이의 x, y 값을 전달하는 콜백을 호출해요. 슬라이더, 컬러 피커 같은 컴포넌트를 만드는 데 사용해요.

출처: 문서

본문

useMove 훅은 사용자가 주어진 요소 위에서 누른 마우스를 움직일 때 호출되는 콜백을 받고, ref와 활성 상태를 가진 객체를 반환해요.

import { useState } from 'react';
import { Group, Text, Code } from '@mantine/core';
import { useMove } from '@mantine/hooks';

function Demo() {
  const [value, setValue] = useState({ x: 0.2, y: 0.6 });
  const { ref, active } = useMove(setValue);

  return (
    <Group style={{ alignItems: 'flex-start' }}>
      <div
        ref={ref}
        style={{
          width: 300,
          height: 200,
          border: '1px solid var(--mantine-color-gray-3)',
          position: 'relative',
        }}
      >
        {/* Filled gradient area */}
      </div>
      <Code>Values {`{ x: ${Math.round(value.x * 100)}, y: ${Math.round(value.y * 100)} }`}</Code>
    </Group>
  );
}

API

x와 y 값은 항상 0과 1 사이에 있어요. 이 값들을 사용해 자신만의 경계 내에서 값을 계산할 수 있어요.

가로 슬라이더 (Horizontal slider)

한 축의 변경을 무시할 수 있어요.

const { ref } = useMove(({ x }) => setValue(x));

세로 슬라이더 (Vertical slider)

슬라이더를 아래로 이동하면 값이 증가해요. 반대로 하려면 setValue 함수에서 값을 1 - y로 설정하세요.

const { ref } = useMove(({ y }) => setValue(1 - y));

clampUseMovePosition

clampUseMovePosition 함수는 x와 y 값을 0-1 범위로 제한하는 데 사용할 수 있어요. 외부 이벤트(예: 키보드 화살표)로 값을 변경하고 싶을 때 유용해요.

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

clampUseMovePosition({ x: 0.5, y: 0.5 }); // -> { x: 0.5, y: 0.5 }
clampUseMovePosition({ x: 1.5, y: 0.5 }); // -> { x: 1, y: 0.5 }
clampUseMovePosition({ x: -0.5, y: 0.5 }); // -> { x: 0, y: 0.5 }

UseMovePosition

@mantine/hooks는 UseMovePosition 타입을 내보내며, 이를 useState의 타입 매개변수로 사용할 수 있어요.

import { useState } from 'react';
import { UseMovePosition } from '@mantine/hooks';

const [value, setValue] = useState<UseMovePosition>({
  x: 0.5,
  y: 0.5,
});

정의 (Definition)

interface UseMovePosition {
  x: number;
  y: number;
}

interface UseMoveHandlers {
  onScrubStart?: () => void;
  onScrubEnd?: () => void;
}

interface UseMoveReturnValue {
  ref: React.RefCallback;
  active: boolean;
}

function useMove(
  onChange: (value: UseMovePosition) => void,
  handlers?: UseMoveHandlers,
  dir?: "ltr" | "rtl",
): UseMoveReturnValue

Exported types

UseMovePosition, UseMoveReturnValue, UseMoveHandlers 타입은 @mantine/hooks 패키지에서 내보내져요.

import type { UseMovePosition, UseMoveHandlers, UseMoveReturnValue } from '@mantine/hooks';

더 알아보기 (Learn more)