FreeMIT License

Dynamic 3D Carousel for React & Next.js — Draggable Image & Video Slider

A draggable 3D carousel for React and Next.js: photo, video and text cards on a curved arc with momentum, a seamless infinite loop, autoplay and a click-to-expand detail view. Built with Motion, keyboard and screen-reader accessible, light and dark.

by UpFork, built by Ramin ValadanComponentUpdated 5 Nov 2026

Read how it was madeBehind the build6 lessons
Watch0
Preview of Dynamic 3D Carousel for React & Next.js — Draggable Image & Video Slider

Code

20 files · 1 package · 40 assets

"use client";

import { AnimatePresence, animate, motion, useMotionValue, useTransform } from "motion/react";
import { useEffect, useId, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from "react";
import { createPortal } from "react-dom";
import { SlideFace } from "./CarouselSlideCard";
import { useIsoLayoutEffect } from "./engine/useCarouselEngine";
import { useFocusTrap } from "./hooks/useFocusTrap";
import { useScrollLock } from "./hooks/useScrollLock";
import { copyVars } from "./portal-vars";
import type { CarouselSlide, RenderImage } from "./types";

/** The morph's spring: a touch softer than the track's snap, so the card visibly travels. */
const MORPH = { type: "spring", stiffness: 210, damping: 28, mass: 1 } as const;
const FADE = { duration: 0.2, ease: "easeOut" } as const;
const CARD_RADIUS = 20;

/** Where an element sits without its own transform (the morph's home), whatever the transform is right now. */
function homeRect(el: HTMLElement | null) {
  if (!el) return null;
  const prev = el.style.transform;
  el.style.transform = "none";
  const rect = el.getBoundingClientRect();
  el.style.transform = prev;
  return rect;
}
const PANEL_RADIUS = 24;

export type CarouselDetailProps = {
  slides: CarouselSlide[];
  index: number;
  aspect: number;
  accent?: string;
  reduced: boolean;
  renderImage?: RenderImage;
  /** The active card's face on screen (the morph starts and ends there), unscaled by the carousel's dip. */
  cardRect: () => DOMRect | null;
  /** The carousel's root: the view takes its fonts and accent from it. */
  varsFrom: () => Element | null;
  /** Element to focus once the view has closed. */
  restoreFocus: () => HTMLElement | null | undefined;
  onNavigate: (index: number) => void;
  /** Called when the close animation has finished. */
  onClosed: () => void;
  /** Called when the close animation starts (the carousel behind can start coming back). */
  onClosing: () => void;
};

function copyFor(s: CarouselSlide) {
  switch (s.kind) {
    case "image":
    case "video":
      return { tag: s.tag, title: s.title ?? s.alt, text: s.description ?? s.caption, href: s.href, cta: s.cta };
    case "statement":
      return { tag: undefined, title: s.word, text: s.description ?? s.subtitle, href: s.href, cta: s.cta };
    case "text":
      return { tag: undefined, title: s.title, text: s.description ?? s.body, href: s.href, cta: s.cta };
    case "stat":
      return { tag: s.delta, title: `${s.value} ${s.label}`, text: s.description, href: s.href, cta: s.cta };
    default:
      return { tag: undefined, title: s.label ?? "Slide", text: undefined, href: undefined, cta: undefined };
  }
}

const Icon = {
  close: (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" aria-hidden>
      <path d="m4 4 8 8M12 4l-8 8" />
    </svg>
  ),
  prev: (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
      <path d="M13 8H3M7 4 3 8l4 4" />
    </svg>
  ),
  next: (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
      <path d="M3 8h10M9 4l4 4-4 4" />
    </svg>
  ),
  out: (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
      <path d="M5 11 11 5M6 5h5v5" />
    </svg>
  ),
};

/**
 * The detail view. The active card's face flies out of the carousel into the view (a FLIP: the large copy is
 * laid out where it belongs, then started from the card's rectangle and sprung home), the copy fades in beside
 * it, and closing sends it back to whichever card is active by then. ← / → move through the slides inside.
 */
export function CarouselDetail(props: CarouselDetailProps) {
  const { slides, index, aspect, accent, reduced, renderImage, cardRect, varsFrom, restoreFocus, onNavigate, onClosed, onClosing } = props;
  const slide = slides[index];
  const count = slides.length;
  const copy = copyFor(slide);
  const titleId = useId();
  const box = useRef<HTMLDivElement>(null);
  const media = useRef<HTMLDivElement>(null);
  const closeBtn = useRef<HTMLButtonElement>(null);
  const [phase, setPhase] = useState<"open" | "closing">("open");
  const [dir, setDir] = useState(1);
  const live = useRef({ closing: false, dragY: 0, pointer: -1, y0: 0, t0: 0 });

  // The morph: translate and scale of the media from the card's rectangle to its own, radius kept visually even.
  const mx = useMotionValue(0);
  const my = useMotionValue(0);
  const ms = useMotionValue(1);
  const backdrop = useMotionValue(0);
  const dragY = useMotionValue(0);
  /** The scale the current morph started from: the radius is eased from the card's to the panel's along it. */
  const s0 = useMotionValue(1);
  const radius = useTransform(() => {
    const s = ms.get();
    const span = 1 - s0.get();
    const t = Math.abs(span) < 0.001 ? 1 : Math.min(1, Math.max(0, (s - s0.get()) / span));
    return `${(CARD_RADIUS + (PANEL_RADIUS - CARD_RADIUS) * t) / s}px`;
  });
  const copyOpacity = useTransform(() => backdrop.get());

  useScrollLock(true);
  useFocusTrap(box, true, { initial: closeBtn, restore: restoreFocus });

  // Open: measure both rectangles before the first paint and start the media on the card.
  useIsoLayoutEffect(() => {
    copyVars(varsFrom(), box.current);
    const to = homeRect(media.current);
    const from = cardRect();
    if (reduced || !to || !from || !to.width) {
      const fade = animate(backdrop, 1, FADE);
      return () => fade.stop();
    }
    const s = from.width / to.width;
    s0.jump(s);
    mx.jump(from.left - to.left);
    my.jump(from.top - to.top);
    ms.jump(s);
    const runs = [animate(mx, 0, MORPH), animate(my, 0, MORPH), animate(ms, 1, MORPH), animate(backdrop, 1, { duration: 0.35, ease: [0.22, 1, 0.36, 1] })];
    return () => runs.forEach((r) => r.stop());
    // Runs once, when the view opens.
  }, []);

  function close() {
    if (live.current.closing) return;
    live.current.closing = true;
    setPhase("closing");
    onClosing();
    // The media's home includes a swipe-down in progress (the sheet carries it), so it lands where it is dropped.
    const home = homeRect(media.current);
    const target = cardRect();
    const fadeOut = animate(backdrop, 0, { duration: reduced ? 0.2 : 0.3, ease: "easeOut" });
    if (reduced || !home || !target || !home.width) {
      fadeOut.finished.then(onClosed);
      return;
    }
    const s = target.width / home.width;
    // Keep the radius formula pointed the same way: card radius at `s`, panel radius at 1.
    s0.jump(s);
    const morph = [animate(mx, target.left - home.left, MORPH), animate(my, target.top - home.top, MORPH), animate(ms, s, MORPH)];
    Promise.all(morph.map((m) => m.finished)).then(onClosed);
  }

  function go(delta: number) {
    if (live.current.closing) return;
    setDir(delta);
    onNavigate((index + delta + count) % count);
  }

  // Keys: Esc closes, ← / → move through the slides (with the carousel behind following along).
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        e.preventDefault();
        close();
      } else if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
        const t = e.target as HTMLElement | null;
        if (t?.closest("input, textarea, [contenteditable]")) return;
        e.preventDefault();
        go(e.key === "ArrowRight" ? 1 : -1);
      }
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  });

  // Swipe down to close (touch).
  const onPointerDown = (e: ReactPointerEvent) => {
    if (e.pointerType !== "touch" || live.current.closing) return;
    live.current.pointer = e.pointerId;
    live.current.y0 = e.clientY;
    live.current.t0 = e.timeStamp;
  };
  const onPointerMove = (e: ReactPointerEvent) => {
    if (e.pointerId !== live.current.pointer) return;
    const dy = Math.max(0, e.clientY - live.current.y0);
    if (box.current && box.current.scrollTop > 0) return;
    dragY.set(dy * 0.85);
    backdrop.set(Math.max(0.35, 1 - dy / 600));
  };
  const onPointerUp = (e: ReactPointerEvent) => {
    if (e.pointerId !== live.current.pointer) return;
    live.current.pointer = -1;
    const dy = dragY.get();
    const v = dy / Math.max(1, e.timeStamp - live.current.t0);
    if (dy > 110 || (dy > 30 && v > 0.6)) close();
    else {
      animate(dragY, 0, MORPH);
      animate(backdrop, 1, FADE);
    }
  };

  const style = { "--dc-aspect": aspect, "--dc-aspect-n": aspect, ...(accent ? { "--dc-accent-now": accent } : {}) } as CSSProperties;

  return createPortal(
    <div
      ref={box}
      className="dc-detail"
      role="dialog"
      aria-modal="true"
      aria-labelledby={titleId}
      style={style}
      data-phase={phase}
      onPointerDown={onPointerDown}
      onPointerMove={onPointerMove}
      onPointerUp={onPointerUp}
      onPointerCancel={onPointerUp}
    >
      <motion.div className="dc-backdrop" style={{ opacity: backdrop }} onClick={close} aria-hidden />
      <motion.div className="dc-sheet" style={{ y: dragY }} onClick={(e) => e.target === e.currentTarget && close()}>
        <motion.div
          ref={media}
          className="dc-detail-media"
          style={{ x: mx, y: my, scale: ms, borderRadius: radius, ...(reduced ? { opacity: copyOpacity } : {}) }}
        >
          <AnimatePresence initial={false} custom={dir}>
            <motion.div
              key={slide.id}
              custom={dir}
              style={{ position: "absolute", inset: 0, borderRadius: "inherit", overflow: "hidden" }}
              initial={reduced ? { opacity: 0 } : { opacity: 0, x: dir * 48 }}
              animate={{ opacity: 1, x: 0 }}
              exit={reduced ? { opacity: 0 } : { opacity: 0, x: dir * -48 }}
              transition={{ duration: 0.42, ease: [0.22, 1, 0.36, 1] }}
            >
              <SlideFace slide={slide} priority sizes="(min-width: 760px) 560px, 92vw" renderImage={renderImage} panel reduced={reduced} />
            </motion.div>
          </AnimatePresence>
        </motion.div>

        <motion.div className="dc-detail-copy" style={{ opacity: copyOpacity }}>
          <AnimatePresence initial={false} mode="wait">
            <motion.div
              key={slide.id}
              style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 18 }}
              initial={{ opacity: 0, y: reduced ? 0 : 10 }}
              animate={{ opacity: 1, y: 0, transition: { duration: 0.4, ease: [0.22, 1, 0.36, 1], delay: 0.05 } }}
              exit={{ opacity: 0, y: reduced ? 0 : -6, transition: { duration: 0.15 } }}
            >
              {copy.tag && <span className="dc-detail-tag">{copy.tag}</span>}
              <h2 id={titleId} className="dc-detail-title">
                {copy.title}
              </h2>
              {copy.text && <p className="dc-detail-text">{copy.text}</p>}
            </motion.div>
          </AnimatePresence>
          <div className="dc-detail-meta">
            <span className="dc-detail-count" aria-live="polite">
              {String(index + 1).padStart(2, "0")} / {String(count).padStart(2, "0")}
            </span>
            <button type="button" className="dc-btn" aria-label="Previous slide" onClick={() => go(-1)}>
              {Icon.prev}
            </button>
            <button type="button" className="dc-btn" aria-label="Next slide" onClick={() => go(1)}>
              {Icon.next}
            </button>
            {copy.href && (
              <a className="dc-detail-cta" href={copy.href}>
                {copy.cta ?? "Open"}
                {Icon.out}
              </a>
            )}
          </div>
        </motion.div>
      </motion.div>
      <motion.button
        ref={closeBtn}
        type="button"
        className="dc-btn dc-detail-close"
        aria-label="Close"
        style={{ opacity: copyOpacity }}
        onClick={close}
      >
        {Icon.close}
      </motion.button>
    </div>,
    document.body,
  );
}
20 files40 assets1 package

From the workbench

Written about Dynamic 3D Carousel for React & Next.js — Draggable Image & Video Slider

By the developer who built it: how it works, with its real code and live preview in the text, and the lessons learned along the way.

About

A draggable 3D carousel for React and Next.js, built for the front page of a studio, a portfolio, a product drop or a magazine. Photo, video and text cards sit on a shallow curved arc and move like real objects: drag them 1:1, flick them with momentum, and they always land exactly on a card. It runs on its own small physics engine, written for this component, with no carousel library underneath.

Features

  • Momentum and snapping. Cards follow your finger or cursor with no lag. A flick carries them with weight and snaps to the nearest card; a quick flick moves one card, a hard one several (never more than half the set).
  • Seamless infinite loop. No cloned slides and no jump back to the start, at any speed. Turn the loop off for a straight rail with rubber-band ends.
  • Real 3D depth. Neighbouring cards turn towards you, step back and dim slightly. Fast motion makes the cards lean into it, and they settle with a small overshoot when they stop. Pictures slide inside their frames (parallax).
  • Six card types. Image and video cards with a tag, title and caption that rise on the active card; a statement card with one huge word; a text card with a script, serif or sans title; a stat card whose number counts up; and your own custom content.
  • Click to expand. The active card morphs into a large detail view with its story and a call to action. Arrow keys move through the slides inside it, and closing returns you to the card you were on.
  • Every input. Mouse drag, touch swipe (vertical page scrolling still works), trackpad and Shift + wheel, a mouse wheel that never traps the page, and the keyboard: arrows, Home, End, Space and Enter.
  • Autoplay with progress. A segmented progress bar fills as it plays. It pauses on hover, keyboard focus, a hidden tab or when the carousel scrolls out of view, and stops for good once the visitor takes control.
  • Polished details. A "Drag" cursor that reads "Open" over the active card, magnetic arrow buttons, paper grain on the colour cards, soft shadows that deepen as a card arrives, and a blurred placeholder while each image loads.
  • Light, dark and auto themes. Auto follows your site's .dark class or colour scheme. Set your fonts and accent colour with CSS variables.
  • Responsive. Full 3D on desktop, a lighter arc on tablets, and on phones a single card with its neighbours peeking and dot indicators. No horizontal page scroll from 320 px up.

Performance

Nothing in React re-renders while the carousel moves: every frame runs on Motion values, using transforms and opacity only. Images load eagerly only near the start, cards far off screen stay mounted but hidden, and the first screen is laid out before any JavaScript runs, so there is no layout shift. About 13 KB gzipped on top of React and Motion.

Accessibility

A labelled carousel region with a single tab stop for the active card, slide announcements for screen readers ("Slide 3 of 9"), visible focus rings, a proper dialog that keeps and returns focus, an always-available pause button, and full support for reduced motion (no springs, no autoplay, a still arc). axe reports no issues, and captions keep a 4.5:1 contrast over the photos.

Install and use

Installs with the shadcn CLI and adds motion (Framer Motion's current name). React 19 (18 works), Next.js App Router or Vite. Plain CSS with dc- classes, so it sits beside Tailwind CSS without touching it.

<DynamicCarousel slides={slides} label="Selected work" />

Props let you set the card width and aspect ratio, gap, loop, autoplay interval, depth, tilt and parallax strength, alignment, theme, accent colour, and whether a click opens the detail view. There is also a ref with next(), prev(), goTo(), pause() and play(), and an onChange callback.

Demos

The preview shows it four ways: an editorial set of ten mixed cards, a dark product rail at full depth, a flat minimal rail, and a complete studio page with all three. Demo photographs come from Unsplash and the ink clip from Pexels; replace them with your own.

Reviews and bugs

0 reviews · 0 bugs

Ship it0With fixes0Skip0· 0 reviews

0 bugs0 open0 fixed

Members who have it review it and report its bugs. Sign in

No reviews or bugs yet.

Manual installation

Without the CLI

  1. 01

    Install the packages

    npm install motion
  2. 02

    Copy the files into your project

    • components/dynamic-carousel/CarouselDetail.tsx
    • components/dynamic-carousel/CarouselProgress.tsx
    • components/dynamic-carousel/CarouselSlideCard.tsx
    • components/dynamic-carousel/DragCursor.tsx
    • components/dynamic-carousel/DynamicCarousel.tsx
    • components/dynamic-carousel/engine/loop.ts
    • components/dynamic-carousel/engine/pose.ts
    • components/dynamic-carousel/engine/snap.ts
    • components/dynamic-carousel/engine/useCarouselEngine.ts
    • components/dynamic-carousel/engine/velocity.ts
    • components/dynamic-carousel/hooks/useDragCursor.ts
    • components/dynamic-carousel/hooks/useFocusTrap.ts
    • components/dynamic-carousel/hooks/useInViewPlayback.ts
    • components/dynamic-carousel/hooks/useMagnetic.ts
    • components/dynamic-carousel/hooks/useReducedMotion.ts
    • components/dynamic-carousel/hooks/useScrollLock.ts
    • components/dynamic-carousel/index.ts
    • components/dynamic-carousel/portal-vars.ts
    • components/dynamic-carousel/styles.css
    • components/dynamic-carousel/types.ts

    The paths follow the shadcn/ui layout, with @/ as your project’s import alias.

  3. 03

    Its pictures and a video load from UpFork

    The code above points at UpFork’s copies (2.0 MB), so there’s nothing to copy. To host them yourself, use Download source: its ZIP has the files where the code expects them, and a README on the switch.

Before you buy

Everything you need to know

How this component gets from the preview into your project, and what buyers ask most.

How to use it

From the preview to your project

  1. 01

    Try it in the preview

    Switch between light and dark, and resize it to phone and tablet widths, before you decide.

  2. 02

    Get it

    Free products are yours with a free account. Paid ones settle in USDT on TRON, sent straight to the wallet on your order.

  3. 03

    Install it

    Components go into your project with one shadcn command, dependencies included. Everything else downloads with a checksum.

  4. 04

    Make it yours

    It's your code now: rename it, restyle it and wire in your real data.

  5. 05

    Or hand it to your AI

    Copy the prompt and let your coding assistant place it in your project, following your conventions.

Building with an AI assistant?

Copy a ready-made prompt with the code, its dependencies and a demo, and your assistant can put it in place for you.

Copy AI prompt

Selling your own work?

Get approved once, then publish components, templates and mobile components, paid in USDT straight to your own wallet.