apps/mantine.dev/src/pages/hooks/use-move.mdx
import { SliderDemos, UseMoveDemos } from '@docs/demos'; import { Layout } from '@/layout'; import { MDX_DATA } from '@/mdx';
export default Layout(MDX_DATA.useMove);
The use-move hook handles move behavior over any element:
The hook accepts a callback that is called when the user moves the pressed mouse over the given element
and returns an object with ref and active state:
import { useMove } from '@mantine/hooks';
const {
ref, // -> pass ref to target element
active, // -> is the user changing something right now?
} = useMove(({ x, y }) => console.log({ x, y }));
The x and y values are always between 0 and 1; you can use them to calculate the value in your boundaries.
You can ignore changes for one of the axis:
<Demo data={UseMoveDemos.horizontal} demoProps={{ toggle: true }} />
Moving the slider down increases the value, to reverse that set value to 1 - y in your setValue function:
<Demo data={UseMoveDemos.vertical} demoProps={{ toggle: true }} />
<Demo data={UseMoveDemos.color} demoProps={{ toggle: true }} />
clampUseMovePosition function can be used to clamp x and y values to 0-1 range.
It is useful when you want to use external events to change the value, for example changing value with keyboard arrows:
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 }
@mantine/hooks exports UseMovePosition type, it can be used as a type parameter for useState:
import { useState } from 'react';
import { UseMovePosition } from '@mantine/hooks';
const [value, setValue] = useState<UseMovePosition>({
x: 0.5,
y: 0.5,
});
interface UseMovePosition {
x: number;
y: number;
}
interface UseMoveHandlers {
onScrubStart?: () => void;
onScrubEnd?: () => void;
}
interface UseMoveReturnValue<T extends HTMLElement = any> {
ref: React.RefCallback<T | null>;
active: boolean;
}
function useMove<T extends HTMLElement = any>(
onChange: (value: UseMovePosition) => void,
handlers?: UseMoveHandlers,
dir?: "ltr" | "rtl",
): UseMoveReturnValue<T>
UseMovePosition, UseMoveReturnValue and UseMoveHandlers types are exported from the @mantine/hooks package;
you can import them in your application:
import type { UseMovePosition, UseMoveHandlers, UseMoveReturnValue } from '@mantine/hooks';