use-tilt

Produces roll/tilt values from pointer and device orientation

Usage

use-tilt returns normalized roll and tilt values based on the pointer position over the target element or, on supported mobile devices, the device orientation. Map these values to CSS transforms to create a tilt effect:

Move your cursor

The edge under the pointer moves away from you

source: mouse · roll: 0.00 · tilt: 0.00

import { Box, Stack, Text, Title } from '@mantine/core';
import { useTilt } from '@mantine/hooks';

function Demo() {
  const { ref, roll, tilt, source } = useTilt<HTMLDivElement>();

  return (
    <Box ref={ref} style={{ perspective: 800, display: 'inline-block' }}>
      <Stack
        align="center"
        justify="center"
        gap={4}
        p="xl"
        style={{
          width: 320,
          height: 220,
          borderRadius: 'var(--mantine-radius-lg)',
          color: 'var(--mantine-color-white)',
          backgroundImage:
            'linear-gradient(135deg, var(--mantine-color-indigo-6), var(--mantine-color-grape-6))',
          transform: `rotateX(${roll * 20}deg) rotateY(${tilt * 20}deg)`,
          transition: 'transform 100ms ease-out',
        }}
      >
        <Title order={3}>Move your cursor</Title>
        <Text>The edge under the pointer moves away from you</Text>
        <Text size="sm" opacity={0.8}>
          source: {source} · roll: {roll.toFixed(2)} · tilt: {tilt.toFixed(2)}
        </Text>
      </Stack>
    </Box>
  );
}

Assign ref to a static wrapper and apply the transform to its child. If the element with ref rotates itself, it flickers near its edges.

If you need a ready-to-use component with glare and layers, use the Tilt component, which is based on this hook.

Definition

interface UseTiltOptions {
  /** If set, the hook reacts to the pointer position anywhere on the page instead of only
   *  when the target element is hovered, false by default */
  trackWindow?: boolean;

  /** If set, roll and tilt reset to 0 when the pointer leaves the target element.
   *  Ignored when the trackWindow option is set to true, true by default */
  resetOnLeave?: boolean;

  /** Adjusts normalized device orientation roll value before it is returned */
  deviceOrientationRollAdjust?: (value: number) => number;

  /** Adjusts normalized device orientation tilt value before it is returned */
  deviceOrientationTiltAdjust?: (value: number) => number;

  /** Adjusts normalized mouse roll value before it is returned */
  mouseRollAdjust?: (value: number) => number;

  /** Adjusts normalized mouse tilt value before it is returned */
  mouseTiltAdjust?: (value: number) => number;
}

interface UseTiltReturnValue<T extends HTMLElement = any> {
  /** Ref callback that must be assigned to the target element */
  ref: React.RefCallback<T | null>;

  /** Vertical tilt normalized to `[-0.5, 0.5]` for mouse input, positive when the pointer is above the center of the element */
  roll: number;

  /** Horizontal tilt normalized to `[-0.5, 0.5]` for mouse input, positive when the pointer is right of the center of the element */
  tilt: number;

  /** Input source that produced the current `roll` and `tilt` values */
  source: 'mouse' | 'deviceOrientation';
}

function useTilt<T extends HTMLElement = any>(
  options?: UseTiltOptions,
): UseTiltReturnValue<T>;

roll and tilt values

roll is the vertical tilt and tilt is the horizontal tilt:

  • Mouse: both values are 0 at the center of the element and approach -0.5/0.5 at the edges. roll is positive above the center, tilt is positive to the right of the center.
  • Device orientation: roll is -beta / 90 and tilt is gamma / 90.

Multiply the values by the number of degrees or pixels you need. With rotateX(roll) and rotateY(tilt), the edge under the pointer moves away from the viewer:

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

function Demo() {
  const { ref, roll, tilt } = useTilt<HTMLDivElement>();

  return (
    <div ref={ref} style={{ perspective: 800 }}>
      <div
        style={{
          transform: `rotateX(${roll * 20}deg) rotateY(${tilt * 20}deg)`,
        }}
      >
        Tilting card
      </div>
    </div>
  );
}

Example: 3D card

Nested layers with different multipliers create a sense of depth:

VISA

4242 4242 4242 4242

Card holder

Jane Cooper

Expires

08 / 28

import { Box, Group, Stack, Text } from '@mantine/core';
import { useTilt } from '@mantine/hooks';

function Demo() {
  const { ref, roll, tilt } = useTilt<HTMLDivElement>();

  // Animate 2x slower when the card returns to its neutral position
  const isNeutral = roll === 0 && tilt === 0;
  const transition = `transform ${isNeutral ? 300 : 150}ms ease-out`;

  return (
    <Box ref={ref} style={{ perspective: 1000, display: 'inline-block' }}>
      <Box
        style={{
          position: 'relative',
          overflow: 'hidden',
          width: 340,
          height: 214,
          padding: 'var(--mantine-spacing-xl)',
          borderRadius: 'var(--mantine-radius-lg)',
          color: 'var(--mantine-color-white)',
          backgroundImage: 'linear-gradient(135deg, #4263eb 0%, #7048e8 55%, #ae3ec9 100%)',
          boxShadow: 'var(--mantine-shadow-xl)',
          transform: `rotateX(${roll * 18}deg) rotateY(${tilt * 18}deg)`,
          transition,
        }}
      >
        <Box
          style={{
            position: 'absolute',
            inset: 0,
            pointerEvents: 'none',
            background:
              'radial-gradient(circle at 50% 50%, rgba(255, 255, 255, 0.45), rgba(255, 255, 255, 0) 55%)',
            transform: `translate(${tilt * 55}%, ${-roll * 55}%)`,
            transition,
          }}
        />

        <Stack justify="space-between" h="100%" gap={0} style={{ position: 'relative' }}>
          <Group justify="space-between" align="flex-start">
            <Box
              style={{
                width: 44,
                height: 32,
                borderRadius: 6,
                backgroundImage: 'linear-gradient(135deg, #ffd43b, #f59f00)',
              }}
            />
            <Text fw={700} fz="lg" fs="italic">
              VISA
            </Text>
          </Group>

          <Text fz="md" ff="monospace" style={{ letterSpacing: 1, whiteSpace: 'nowrap' }}>
            4242 4242 4242 4242
          </Text>

          <Group justify="space-between">
            <Stack gap={2}>
              <Text fz={10} opacity={0.7} tt="uppercase">Card holder</Text>
              <Text fw={500}>Jane Cooper</Text>
            </Stack>
            <Stack gap={2}>
              <Text fz={10} opacity={0.7} tt="uppercase">Expires</Text>
              <Text fw={500}>08 / 28</Text>
            </Stack>
          </Group>
        </Stack>
      </Box>
    </Box>
  );
}

Reset on leave

By default, roll and tilt reset to 0 when the pointer leaves the target element. Set resetOnLeave: false to keep the last values:

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

function Demo() {
  // The element keeps its last tilt after the cursor leaves
  const { ref, roll, tilt } = useTilt<HTMLDivElement>({ resetOnLeave: false });
  // ...
}

React to the whole page

By default, the hook updates the values only while the target element is hovered. Set trackWindow: true to react to the pointer position anywhere on the page:

Move your cursor anywhere on the page

import { Box, Text } from '@mantine/core';
import { clamp, useTilt } from '@mantine/hooks';

function Demo() {
  // With trackWindow: true the effect follows the cursor everywhere on the page,
  // not only while the element is hovered
  const { ref, roll, tilt } = useTilt<HTMLDivElement>({ trackWindow: true });

  return (
    <Box
      style={{
        perspective: 1000,
        minHeight: 260,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <Box ref={ref} style={{ display: 'inline-block' }}>
        <Box
          style={{
            transform: `rotateX(${clamp(roll, -0.5, 0.5) * 30}deg) rotateY(${clamp(tilt, -0.5, 0.5) * 30}deg)`,
            transition: 'transform 120ms ease-out',
            width: 200,
            height: 200,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            textAlign: 'center',
            padding: 'var(--mantine-spacing-md)',
            fontWeight: 600,
            color: 'var(--mantine-color-white)',
            borderRadius: 'var(--mantine-radius-lg)',
            backgroundImage: 'radial-gradient(circle at 30% 30%, #4dabf7, #1971c2)',
            boxShadow: 'var(--mantine-shadow-lg)',
          }}
        >
          <Text inherit>Move your cursor anywhere on the page</Text>
        </Box>
      </Box>
    </Box>
  );
}

With trackWindow, the values are not clamped to [-0.5, 0.5] – they grow the further the cursor is from the element. Use the adjust options to limit the effect.

Adjusting values

Use the *Adjust options to amplify, dampen, clamp or invert the values of each input source. In the example below, the mouse values are inverted and amplified, so the edge under the cursor moves towards the viewer:

The edge under the cursor lifts towards you

roll: 0.00 · tilt: 0.00

import { Box, Stack, Text } from '@mantine/core';
import { useTilt } from '@mantine/hooks';

function Demo() {
  const { ref, roll, tilt } = useTilt<HTMLDivElement>({
    mouseRollAdjust: (value) => -value * 1.6,
    mouseTiltAdjust: (value) => -value * 1.6,
  });

  return (
    <Box ref={ref} style={{ perspective: 800, display: 'inline-block' }}>
      <Stack
        align="center"
        justify="center"
        gap={4}
        p="xl"
        style={{
          transform: `rotateX(${roll * 20}deg) rotateY(${tilt * 20}deg)`,
          transition: 'transform 100ms ease-out',
          width: 320,
          height: 220,
          color: 'var(--mantine-color-white)',
          borderRadius: 'var(--mantine-radius-lg)',
          backgroundImage:
            'linear-gradient(135deg, var(--mantine-color-teal-6), var(--mantine-color-cyan-7))',
        }}
      >
        <Text fw={600} fz="lg">
          The edge under the cursor lifts towards you
        </Text>
        <Text size="sm" opacity={0.8}>
          roll: {roll.toFixed(2)} · tilt: {tilt.toFixed(2)}
        </Text>
      </Stack>
    </Box>
  );
}
import { useTilt } from '@mantine/hooks';

function Demo() {
  const { ref, roll, tilt } = useTilt<HTMLDivElement>({
    // Amplify the mouse effect
    mouseRollAdjust: (value) => value * 2,
    mouseTiltAdjust: (value) => value * 2,
    // Invert the device orientation effect
    deviceOrientationRollAdjust: (value) => -value,
    deviceOrientationTiltAdjust: (value) => -value,
  });

  // ...
}

Source selection

source is the active input: 'mouse' or 'deviceOrientation'. Once the device reports orientation data, the hook switches to deviceOrientation and keeps using it. Use source to display input-specific hints, for example "move the cursor" or "tilt the device".

Device orientation permission

On iOS 13+, access to device orientation requires a permission. use-tilt does not request it – call DeviceOrientationEvent.requestPermission() from an event handler, for example a button click. Until the permission is granted, the hook uses the pointer position:

async function requestOrientationPermission() {
  const DeviceOrientationEventTyped = DeviceOrientationEvent as unknown as {
    requestPermission?: () => Promise<'granted' | 'denied'>;
  };

  if (typeof DeviceOrientationEventTyped.requestPermission === 'function') {
    await DeviceOrientationEventTyped.requestPermission();
  }
}

Exported types

UseTiltOptions, UseTiltReturnValue and UseTiltSource types are exported from the @mantine/hooks package, you can import them in your application:

import type {
  UseTiltOptions,
  UseTiltReturnValue,
  UseTiltSource,
} from '@mantine/hooks';