Image Compare
A before/after image comparison slider for React and Tailwind CSS: drag the divider with mouse, pen or touch, follow the cursor in hover mode, or step it with the keyboard to reveal one layer over another through a clip-path. Works horizontally or vertically with any two children — photos, SVGs, or whole components — and never re-renders while dragging.
- Drag, touch & hover
- Horizontal / vertical
- Any two layers
- Slider a11y
- No re-renders
- prefers-reduced-motion
import { ImageCompare } from "@/components/dusk/image-compare/image-compare";
// [x, width, height] of each tower, fixed so server and client markup match.
const towers = [
[0, 46, 120], [42, 34, 168], [72, 52, 96], [120, 30, 196], [146, 58, 142],
[200, 36, 222], [232, 48, 128], [276, 40, 176], [312, 56, 108], [364, 38, 156],
] as const;
function Skyline({ variant }: { variant: "sketch" | "render" }) {
const render = variant === "render";
return (
<svg viewBox="0 0 400 250" preserveAspectRatio="xMidYMid slice" role="img" aria-label={render ? "Rendered neon skyline" : "Wireframe sketch of a skyline"}>
<defs>
<linearGradient id={`sky-${variant}`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stopColor={render ? "#1b0b3a" : "#0b0f0d"} />
<stop offset="0.65" stopColor={render ? "#4a1550" : "#0e1411"} />
<stop offset="1" stopColor={render ? "#ff6a7a" : "#121a16"} />
</linearGradient>
<radialGradient id={`moon-${variant}`}>
<stop offset="0" stopColor="#fef3c7" stopOpacity="0.9" />
<stop offset="1" stopColor="#fef3c7" stopOpacity="0" />
</radialGradient>
<pattern id={`grid-${variant}`} width="20" height="20" patternUnits="userSpaceOnUse">
<path d="M20 0H0V20" fill="none" stroke="rgb(255 255 255 / 0.06)" />
</pattern>
</defs>
<rect width="400" height="250" fill={`url(#sky-${variant})`} />
{render ? (
<>
<circle cx="318" cy="62" r="46" fill="url(#moon-render)" />
<circle cx="318" cy="62" r="16" fill="#fef3c7" />
</>
) : (
<>
<rect width="400" height="250" fill="url(#grid-sketch)" />
<circle cx="318" cy="62" r="16" fill="none" stroke="rgb(255 255 255 / 0.35)" strokeDasharray="3 3" />
</>
)}
{towers.map(([x, w, h], i) => (
<g key={i}>
<rect
x={x}
y={250 - h}
width={w}
height={h}
fill={render ? "#0a0614" : "none"}
stroke={render ? "rgb(255 255 255 / 0.04)" : "rgb(255 255 255 / 0.4)"}
strokeDasharray={render ? undefined : "4 3"}
/>
{Array.from({ length: Math.floor(h / 22) }, (_, row) =>
Array.from({ length: Math.floor(w / 14) }, (_, col) => {
const lit = (i * 7 + row * 3 + col * 5) % 4 !== 0;
return (
<rect
key={`${row}-${col}`}
x={x + 5 + col * 14}
y={250 - h + 8 + row * 22}
width="6"
height="9"
rx="1"
fill={render ? (lit ? ((i + col) % 3 ? "#f3e3b5" : "#d9c79a") : "#1a1325") : "none"}
fillOpacity={render ? (lit ? 0.85 : 1) : 0}
stroke={render ? "none" : "rgb(255 255 255 / 0.18)"}
/>
);
})
)}
</g>
))}
</svg>
);
}
export default function ImageCompareDemo() {
return (
<ImageCompare
className="max-w-xl"
label="Compare wireframe and render"
beforeLabel="Sketch"
afterLabel="Render"
before={<Skyline variant="sketch" />}
after={<Skyline variant="render" />}
/>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/image-compare.json1. Install the dependencies.
npm install motion lucide-react2. Copy the source into
components/dusk/image-compare/image-compare.tsx.image-compare.tsx "use client"; import * as React from "react"; import { animate, motion, useMotionTemplate, useMotionValue, useMotionValueEvent, useReducedMotion, useTransform, type AnimationPlaybackControls, } from "motion/react"; import { ChevronsLeftRight, ChevronsUpDown } from "lucide-react"; import { cn } from "@/lib/utils"; const glide = { type: "spring", stiffness: 380, damping: 36 } as const; const clamp = (value: number) => Math.min(100, Math.max(0, value)); export interface ImageCompareProps extends Omit<React.ComponentProps<"div">, "children" | "defaultValue" | "onChange"> { /** Layer revealed on the left (or top). Any element: an <img>, a component, a canvas… It is stretched to fill. */ before: React.ReactNode; /** Layer revealed on the right (or bottom). */ after: React.ReactNode; /** Small badge in the corner of the before layer. A string also names the layer for screen readers. */ beforeLabel?: React.ReactNode; /** Small badge in the corner of the after layer. */ afterLabel?: React.ReactNode; /** Direction the divider travels. */ orientation?: "horizontal" | "vertical"; /** Controlled divider position in percent (0 = all after, 100 = all before). */ position?: number; /** Starting position when uncontrolled. */ defaultPosition?: number; /** Called with the new position (0–100) while dragging, hovering or using the keyboard. */ onPositionChange?: (position: number) => void; /** `drag` follows a press-and-drag; `hover` follows the mouse without pressing (touch still drags). */ mode?: "drag" | "hover"; /** Percent moved per arrow key press. Page Up / Page Down move 10. */ step?: number; /** Accessible name of the slider. */ label?: string; } /** * A before/after comparison slider that reveals one layer over another with a clip-path as you drag the divider, hover, or use the keyboard. */ export function ImageCompare({ before, after, beforeLabel, afterLabel, orientation = "horizontal", position: positionProp, defaultPosition = 50, onPositionChange, mode = "drag", step = 2, label = "Comparison slider", className, onPointerDown, onPointerMove, onPointerUp, onPointerCancel, ...props }: ImageCompareProps) { const horizontal = orientation === "horizontal"; const reduceMotion = useReducedMotion(); const rootRef = React.useRef<HTMLDivElement>(null); const knobRef = React.useRef<HTMLDivElement>(null); const dragging = React.useRef(false); const animation = React.useRef<AnimationPlaybackControls | null>(null); const [initial] = React.useState(() => clamp(positionProp ?? defaultPosition)); // The divider lives in a motion value so dragging never re-renders React. const pos = useMotionValue(initial); const clipPath = useTransform(pos, (v) => horizontal ? `inset(0 ${100 - v}% 0 0)` : `inset(0 0 ${100 - v}% 0)` ); const offset = useMotionTemplate`${pos}%`; const beforeName = typeof beforeLabel === "string" ? beforeLabel : "before"; const afterName = typeof afterLabel === "string" ? afterLabel : "after"; const valueText = (v: number) => { const rounded = Math.round(v); return `${rounded}% ${beforeName}, ${100 - rounded}% ${afterName}`; }; // Keep the slider's aria values in sync without a render per frame. useMotionValueEvent(pos, "change", (v) => { const knob = knobRef.current; if (!knob) return; knob.setAttribute("aria-valuenow", String(Math.round(v))); knob.setAttribute("aria-valuetext", valueText(v)); }); // Follow the controlled prop. React.useEffect(() => { if (positionProp === undefined) return; const next = clamp(positionProp); if (Math.abs(next - pos.get()) < 0.01) return; animation.current?.stop(); if (reduceMotion || dragging.current) pos.set(next); else animation.current = animate(pos, next, glide); }, [positionProp, pos, reduceMotion]); React.useEffect(() => () => animation.current?.stop(), []); const moveTo = (value: number, animated: boolean) => { const next = clamp(value); animation.current?.stop(); if (animated && !reduceMotion) animation.current = animate(pos, next, glide); else pos.set(next); onPositionChange?.(next); }; const fromPointer = (event: React.PointerEvent) => { const rect = rootRef.current!.getBoundingClientRect(); const ratio = horizontal ? (event.clientX - rect.left) / rect.width : (event.clientY - rect.top) / rect.height; return ratio * 100; }; const setDragging = (value: boolean) => { dragging.current = value; const root = rootRef.current; if (!root) return; if (value) root.dataset.dragging = ""; else delete root.dataset.dragging; }; const hoverFollows = (event: React.PointerEvent) => mode === "hover" && event.pointerType === "mouse"; const handleKeyDown = (event: React.KeyboardEvent) => { const current = pos.get(); // Arrows move the divider the way they point; Up/Down follow the WAI-ARIA slider rule horizontally. const forward = horizontal ? ["ArrowRight", "ArrowUp"] : ["ArrowRight", "ArrowDown"]; const backward = horizontal ? ["ArrowLeft", "ArrowDown"] : ["ArrowLeft", "ArrowUp"]; let next: number | null = null; if (forward.includes(event.key)) next = current + step; else if (backward.includes(event.key)) next = current - step; else if (event.key === (horizontal ? "PageUp" : "PageDown")) next = current + 10; else if (event.key === (horizontal ? "PageDown" : "PageUp")) next = current - 10; else if (event.key === "Home") next = 0; else if (event.key === "End") next = 100; if (next === null) return; event.preventDefault(); moveTo(next, event.key === "Home" || event.key === "End" || event.key.startsWith("Page")); }; const badge = "pointer-events-none absolute z-10 rounded-full border border-white/10 bg-background/70 px-2.5 py-1 text-xs font-medium text-foreground/90 backdrop-blur-md"; return ( <div ref={rootRef} data-slot="image-compare" data-orientation={orientation} className={cn( "group/compare relative isolate aspect-[16/10] w-full overflow-hidden rounded-xl border bg-muted select-none", horizontal ? "cursor-ew-resize touch-pan-y" : "cursor-ns-resize touch-pan-x", className )} onPointerDown={(event) => { onPointerDown?.(event); if (event.defaultPrevented || event.button !== 0 || hoverFollows(event)) return; // Stop native image dragging and text selection; focus the handle ourselves. event.preventDefault(); knobRef.current?.focus({ preventScroll: true }); event.currentTarget.setPointerCapture(event.pointerId); setDragging(true); moveTo(fromPointer(event), true); }} onPointerMove={(event) => { onPointerMove?.(event); if (dragging.current || hoverFollows(event)) moveTo(fromPointer(event), false); }} onPointerUp={(event) => { onPointerUp?.(event); setDragging(false); }} onPointerCancel={(event) => { onPointerCancel?.(event); setDragging(false); }} {...props} > <div className="absolute inset-0 *:size-full [&_img]:pointer-events-none [&_img]:object-cover"> {after} </div> {afterLabel ? ( <span className={cn(badge, horizontal ? "top-3 right-3" : "bottom-3 left-3")}>{afterLabel}</span> ) : null} <motion.div className="absolute inset-0 z-[1] [&_img]:pointer-events-none [&_img]:object-cover" style={{ clipPath, WebkitClipPath: clipPath }} > <div className="absolute inset-0 *:size-full">{before}</div> {beforeLabel ? <span className={cn(badge, "top-3 left-3")}>{beforeLabel}</span> : null} </motion.div> {/* Divider + handle. The root takes the pointer; the knob is only the keyboard target. */} <motion.div className={cn("pointer-events-none absolute z-20", horizontal ? "inset-y-0 w-0" : "inset-x-0 h-0")} style={horizontal ? { left: offset } : { top: offset }} > <span aria-hidden className={cn( "absolute bg-white/90", horizontal ? "inset-y-0 -left-px w-0.5" : "inset-x-0 -top-px h-0.5" )} /> <div ref={knobRef} role="slider" tabIndex={0} aria-label={label} aria-orientation={orientation} aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(positionProp ?? initial)} aria-valuetext={valueText(positionProp ?? initial)} onKeyDown={handleKeyDown} className={cn( "absolute grid size-9 place-items-center rounded-full border border-white/20 bg-background text-foreground shadow-md outline-none", "transition-colors duration-150 ease-out motion-reduce:transition-none", "group-data-[dragging]/compare:bg-accent", "focus-visible:ring-[3px] focus-visible:ring-ring/60", horizontal ? "top-1/2 left-0 -translate-x-1/2 -translate-y-1/2" : "top-0 left-1/2 -translate-x-1/2 -translate-y-1/2" )} > {horizontal ? ( <ChevronsLeftRight aria-hidden className="size-4" /> ) : ( <ChevronsUpDown aria-hidden className="size-4" /> )} </div> </motion.div> </div> ); }
Usage
import { ImageCompare } from "@/components/dusk/image-compare/image-compare"
export function PhotoEdit() {
return (
<ImageCompare
className="aspect-video max-w-2xl"
beforeLabel="Original"
afterLabel="Edited"
before={<img src="/original.jpg" alt="Original photo" />}
after={<img src="/edited.jpg" alt="Color-graded photo" />}
/>
)
}Examples
Vertical
orientation="vertical" moves the divider top to bottom. Size the frame with any aspect-ratio class; both layers stretch to fill it.
import { ImageCompare } from "@/components/dusk/image-compare/image-compare";
const palettes = {
day: { sky: ["#7dd3fc", "#e0f2fe"], far: "#5b8fb0", mid: "#3f7a6b", near: "#25543f", sun: "#fff7d6" },
dusk: { sky: ["#0b0620", "#5b1d5e"], far: "#2a1846", mid: "#1a1033", near: "#0b0718", sun: "#ffd1a8" },
};
function Landscape({ time }: { time: keyof typeof palettes }) {
const p = palettes[time];
return (
<svg viewBox="0 0 300 400" preserveAspectRatio="xMidYMid slice" role="img" aria-label={`Mountains at ${time}`}>
<defs>
<linearGradient id={`land-sky-${time}`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stopColor={p.sky[0]} />
<stop offset="1" stopColor={p.sky[1]} />
</linearGradient>
</defs>
<rect width="300" height="400" fill={`url(#land-sky-${time})`} />
<circle cx="210" cy={time === "day" ? 90 : 210} r="26" fill={p.sun} opacity={time === "day" ? 1 : 0.85} />
{time === "dusk" &&
[
[30, 40], [80, 22], [140, 64], [250, 30], [190, 110], [60, 130], [270, 150],
].map(([x, y]) => <circle key={`${x}-${y}`} cx={x} cy={y} r="1.2" fill="#fff" opacity="0.8" />)}
<path d="M0 250 L60 180 L110 230 L170 150 L240 220 L300 170 L300 400 L0 400Z" fill={p.far} />
<path d="M0 300 L50 250 L120 300 L190 240 L260 290 L300 260 L300 400 L0 400Z" fill={p.mid} />
<path d="M0 350 L80 310 L150 345 L230 305 L300 335 L300 400 L0 400Z" fill={p.near} />
</svg>
);
}
export default function ImageCompareVerticalDemo() {
return (
<ImageCompare
orientation="vertical"
defaultPosition={45}
className="aspect-[3/4] max-w-[18rem]"
label="Compare day and dusk"
beforeLabel="Day"
afterLabel="Dusk"
before={<Landscape time="day" />}
after={<Landscape time="dusk" />}
/>
);
}Hover to compare
With mode="hover" the divider follows the mouse without pressing. Touch screens still drag. The layers here are live components, not images.
Monthly revenue
$48,210
Monthly revenue
$48,210
import { ImageCompare } from "@/components/dusk/image-compare/image-compare";
function StatCard({ styled }: { styled: boolean }) {
return (
<div
className={
styled
? "grid place-items-center bg-background"
: "grid place-items-center bg-neutral-200"
}
>
<div
className={
styled
? "w-56 rounded-xl border bg-card p-5 shadow-sm"
: "w-56 rounded border border-neutral-400 bg-white p-5"
}
>
<p className={styled ? "text-xs text-muted-foreground" : "text-xs text-neutral-500"}>Monthly revenue</p>
<p className={styled ? "mt-1 text-3xl font-semibold text-foreground tabular-nums" : "mt-1 text-3xl font-semibold text-neutral-900 tabular-nums"}>
$48,210
</p>
<div className="mt-4 flex h-12 items-end gap-1.5">
{[38, 52, 44, 70, 62, 88, 100].map((h, i) => (
<span
key={i}
style={{ height: `${h}%` }}
className={styled ? "flex-1 rounded-sm bg-primary/80" : "flex-1 bg-neutral-400"}
/>
))}
</div>
</div>
</div>
);
}
export default function ImageCompareHoverDemo() {
return (
<ImageCompare
mode="hover"
defaultPosition={50}
className="aspect-video max-w-lg"
label="Compare default and DuskUI styles"
beforeLabel="Default"
afterLabel="DuskUI"
before={<StatCard styled={false} />}
after={<StatCard styled />}
/>
);
}API Reference
Also accepts any div attribute. Give it a size with className (it defaults to aspect-[16/10] w-full).
| Prop | Type | Default | Description |
|---|---|---|---|
| before | ReactNode | — | Layer shown on the left (or top). Stretched to fill; images get object-cover. |
| after | ReactNode | — | Layer shown on the right (or bottom). |
| beforeLabel / afterLabel | ReactNode | — | Corner badges. Strings also name the layers in the slider's value text. |
| orientation | "horizontal" | "vertical" | "horizontal" | Direction the divider travels. |
| mode | "drag" | "hover" | "drag" | Press-and-drag, or follow the mouse. Touch always drags. |
| position | number | — | Controlled position in percent: how much of the before layer is visible. |
| defaultPosition | number | 50 | Starting position when uncontrolled. |
| onPositionChange | (position: number) => void | — | Called as the divider moves. |
| step | number | 2 | Percent per arrow key. Page Up / Page Down move 10. |
| label | string | "Comparison slider" | Accessible name of the slider. |
Accessibility
- The handle is a focusable
role="slider"witharia-valuenow,aria-orientationand value text such as “40% before, 60% after”. - Arrow keys move the divider by step, Page Up / Page Down by 10%, Home and End jump to either edge.
- Pressing anywhere on the frame jumps the divider there and focuses the handle, so keyboard and pointer stay in sync.
- Horizontal sliders keep vertical page scrolling on touch (
touch-action: pan-y), vertical ones keep horizontal scrolling. - Give images meaningful alt text — both layers stay in the accessibility tree.
- With prefers-reduced-motion, clicks and keyboard jumps snap instead of gliding.