Carousel
Horizontal drag carousel using framer-motion drag constraints. Elastic bounce at edges.
Use and inspectUse this when the motion supports the surrounding content. Connect callbacks and state to your app, keep the reset preview as a local demonstration, and add a reduced-motion fallback for movement or looping. The preview is synthetic; it does not call a backend.Next: inspect the source below and replace the demo inputs with your own data.
CarouselHorizontal drag carousel using framer-motion drag constraints. Elastic bounce at edges.
"use client";
import { useRef } from "react";
import { motion } from "framer-motion";
type CarouselProps = {
children: React.ReactNode[];
gap?: number;
};
export function Carousel({ children, gap = 12 }: CarouselProps) {
const constraintsRef = useRef<HTMLDivElement>(null);
const itemWidth = 180;
const totalWidth = children.length * (itemWidth + gap);
const containerWidth = 320;
const maxDrag = -(totalWidth - containerWidth);
return (
<div ref={constraintsRef} className="mp-carousel">
<motion.div
className="mp-carousel-track"
drag="x"
dragConstraints={{ left: maxDrag < 0 ? maxDrag : 0, right: 0 }}
dragElastic={0.08}
dragTransition={{ bounceStiffness: 300, bounceDamping: 30 }}
style={{ gap }}
>
{children.map((child, i) => (
<div key={i} className="mp-carousel-item" style={{ minWidth: itemWidth }}>
{child}
</div>
))}
</motion.div>
</div>
);
}Install
npm install framer-motionProps
| Prop | Type | Default | Description |
|---|---|---|---|
| childrenrequired | ReactNode[] | — | Carousel items |
| gap | number | 12 | Gap between items in px |