DocumentationMagnetic

Magnetic

Pulls an isolated child toward a fine pointer and settles with a spring.

Svelte

Shared live previews stay running while you switch code examples and API documentation.

Restrained pull

Quick start

Add to your project

Copy the component and everything it needs into your React project.

RecommendedUse the shadcn CLI
npx shadcn@latest add https://kida-ui.onrender.com/r/magnetic.json

Run this from a project with components.json. The CLI creates all required files and installs the declared runtime dependencies. New to shadcn? Follow theinstallation guide first.

View registry JSON
Copy manually6 files

1. Install runtime dependencies

npm install motion@^13.1.0

2. Create the source files

Keep this directory structure so the component's relative imports continue to work.

src/components/ui/kida/magnetic.tsx
'use client'

import './magnetic.css'
import { type MagneticOptions, magnetic } from './motion/magnetic.js'
import type { HTMLAttributes, ReactNode } from 'react'
import { forwardRef, useRef } from 'react'
import { composeRefs } from './compose-refs.js'
import { useIsomorphicLayoutEffect } from './use-isomorphic-layout-effect.js'

export interface MagneticProps extends MagneticOptions, HTMLAttributes<HTMLSpanElement> {
  children?: ReactNode
  targetClassName?: string
}

export const Magnetic = forwardRef<HTMLSpanElement, MagneticProps>(function Magnetic(
  { strength, maxDistance, children, targetClassName, ...props },
  forwardedRef,
) {
  const rootRef = useRef<HTMLSpanElement>(null)
  const targetRef = useRef<HTMLSpanElement>(null)

  useIsomorphicLayoutEffect(() => {
    const root = rootRef.current
    const target = targetRef.current
    if (!root || !target) return
    return magnetic(root, target, { strength, maxDistance })
  }, [maxDistance, strength])

  return (
    <span {...props} ref={composeRefs(rootRef, forwardedRef)} data-kida-magnetic="">
      <span ref={targetRef} className={targetClassName} data-kida-magnetic-target="">
        {children}
      </span>
    </span>
  )
})
src/components/ui/kida/compose-refs.ts
import type { Ref } from 'react'

/** Feed one node to several refs — ours for measuring, Zag's for animation detection. */
export function composeRefs<T>(...refs: (Ref<T> | undefined)[]) {
  return (node: T | null) => {
    for (const ref of refs) {
      if (typeof ref === 'function') ref(node)
      else if (ref) (ref as { current: T | null }).current = node
    }
  }
}
src/components/ui/kida/use-isomorphic-layout-effect.ts
'use client'

import { useEffect, useLayoutEffect } from 'react'

/**
 * `useLayoutEffect` in the browser, `useEffect` on the server.
 *
 * Motion has to be applied before paint or the user sees an unstyled frame, but React
 * warns when `useLayoutEffect` runs during SSR — where it does nothing anyway.
 */
export const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect
src/components/ui/kida/magnetic.css
[data-kida-magnetic] {
  --kida-magnetic-activation-distance: 2rem;

  display: inline-flex;
  position: relative;
  isolation: isolate;
}

/* Keep hover detection around the stationary root. Without this stable area, translating
   the target can move it out from under the pointer and immediately cancel the effect. */
[data-kida-magnetic]::before {
  position: absolute;
  z-index: -1;
  inset: calc(-1 * var(--kida-magnetic-activation-distance));
  content: "";
}

[data-kida-magnetic-target] {
  display: inline-flex;
}

@media (prefers-reduced-motion: reduce) {
  [data-kida-magnetic-target] {
    /* biome-ignore lint/complexity/noImportantStyles: stops an in-flight inline transform */
    transform: none !important;
  }
}
src/components/ui/kida/motion/magnetic.ts
import { motionValue, springValue, styleEffect } from 'motion'
import { prefersReducedMotion } from './reduced-motion.js'

export interface MagneticOptions {
  /** Portion of pointer distance followed by the target. @default 0.22 */
  strength?: number
  /** Maximum travel in CSS pixels. @default 18 */
  maxDistance?: number
}

const DEFAULTS = { strength: 0.22, maxDistance: 18 } as const

export function magnetic(
  root: HTMLElement,
  target: HTMLElement,
  options: MagneticOptions = {},
): () => void {
  if (prefersReducedMotion()) return () => {}

  const { strength = DEFAULTS.strength, maxDistance = DEFAULTS.maxDistance } = options
  let bounds = root.getBoundingClientRect()
  let frame = 0
  let x = 0
  let y = 0
  let inside = false

  // Retarget one persistent spring instead of canceling and recreating a DOM animation
  // for every pointer frame. Recreating it continually throws away most of the spring's
  // velocity, which makes a moving pointer look as though it barely affects the target.
  const sourceX = motionValue(0)
  const sourceY = motionValue(0)
  const spring = { stiffness: 360, damping: 24, mass: 0.65 }
  const springX = springValue(sourceX, spring)
  const springY = springValue(sourceY, spring)
  const stopStyleEffect = styleEffect(target, { x: springX, y: springY })

  let xSettled = true
  let ySettled = true
  const settle = () => {
    if (inside || !xSettled || !ySettled || sourceX.get() !== 0 || sourceY.get() !== 0) return
    target.style.transform = 'none'
    target.style.willChange = 'auto'
  }
  const stopXStart = springX.on('animationStart', () => {
    xSettled = false
  })
  const stopYStart = springY.on('animationStart', () => {
    ySettled = false
  })
  const stopXComplete = springX.on('animationComplete', () => {
    xSettled = true
    settle()
  })
  const stopYComplete = springY.on('animationComplete', () => {
    ySettled = true
    settle()
  })

  const move = () => {
    frame = 0
    sourceX.set(x)
    sourceY.set(y)
  }

  const onEnter = () => {
    inside = true
    bounds = root.getBoundingClientRect()
    target.style.willChange = 'transform'
  }
  const onMove = (event: PointerEvent) => {
    if (event.pointerType === 'touch') return
    const centerX = bounds.left + bounds.width / 2
    const centerY = bounds.top + bounds.height / 2
    x = Math.max(-maxDistance, Math.min(maxDistance, (event.clientX - centerX) * strength))
    y = Math.max(-maxDistance, Math.min(maxDistance, (event.clientY - centerY) * strength))
    if (!frame) frame = requestAnimationFrame(move)
  }
  const onLeave = () => {
    inside = false
    if (frame) cancelAnimationFrame(frame)
    frame = 0
    x = 0
    y = 0
    sourceX.set(0)
    sourceY.set(0)
    settle()
  }

  root.addEventListener('pointerenter', onEnter)
  root.addEventListener('pointermove', onMove)
  root.addEventListener('pointerleave', onLeave)
  const observer = new ResizeObserver(() => {
    bounds = root.getBoundingClientRect()
  })
  observer.observe(root)

  return () => {
    root.removeEventListener('pointerenter', onEnter)
    root.removeEventListener('pointermove', onMove)
    root.removeEventListener('pointerleave', onLeave)
    observer.disconnect()
    if (frame) cancelAnimationFrame(frame)
    stopXStart()
    stopYStart()
    stopXComplete()
    stopYComplete()
    stopStyleEffect()
    springX.destroy()
    springY.destroy()
    sourceX.destroy()
    sourceY.destroy()
    target.style.transform = 'none'
    target.style.willChange = 'auto'
  }
}
src/components/ui/kida/motion/reduced-motion.ts
const QUERY = '(prefers-reduced-motion: reduce)'

/**
 * Whether the user has asked for reduced motion.
 *
 * SSR-safe: returns `false` when there is no `window`, matching the CSS default
 * (the `prefers-reduced-motion` media query in `@kida-ui/styles` is the real guard;
 * this is for the JS-driven paths that CSS cannot express).
 */
export function prefersReducedMotion(): boolean {
  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false
  return window.matchMedia(QUERY).matches
}

/**
 * Subscribe to changes of the reduced-motion preference.
 * Returns an unsubscribe function. No-op (and immediately unsubscribable) on the server.
 */
export function watchReducedMotion(onChange: (reduced: boolean) => void): () => void {
  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return () => {}

  const list = window.matchMedia(QUERY)
  const handler = (event: MediaQueryListEvent) => onChange(event.matches)
  list.addEventListener('change', handler)
  return () => list.removeEventListener('change', handler)
}
import { Magnetic } from '@/components/ui/kida/magnetic'

export default function MagneticExample() {
  return (
    <Magnetic>
      <button type="button">Come closer</button>
    </Magnetic>
  )
}

API

Props

Prop Type Default Description
strength number 0.22 Portion of pointer distance followed.
maxDistance number 18 Maximum travel in CSS pixels.
targetClassName string — Class applied to the isolated moving layer.

The root also accepts span attributes, className, style, event handlers, and a forwarded ref.

CSS custom properties

Property Default Description
--kida-magnetic-activation-distance 2rem Stable pointer area around the stationary root.

Customization

Use strength to tune how closely the child follows the pointer and maxDistance to cap its travel. --kida-magnetic-activation-distance controls the stationary hover area; keep it large enough that the moving child cannot escape the pointer too easily.

Accessibility and input behavior

Only mouse and pen movement activate the effect. Touch input is ignored, and the wrapped control continues to own its click, focus, and keyboard behavior. Magnetic does not reveal information, so no keyboard-only motion is required.

When reduced motion is requested, pointer tracking is disabled and the child stays in its natural position. The stationary root keeps the hit area predictable while the visible child moves.

Troubleshooting

Magnetic intentionally ignores touch input and does not move under reduced motion. Test with a mouse or pen, and avoid applying another transform directly to the generated target layer.