View as Markdown

Shadcn Comparison

A before and after slider that stacks two layers and reveals one over the other. It works with images and any other content, horizontally or vertically, by dragging or by hovering. The handle is a real slider, so it works with the keyboard and screen readers out of the box.

Mountain range in color
Mountain range in black and white

Installation

npx shadcn@latest add @shadcnuikit/comparison1

This adds components/ui/comparison.tsx, the badge component it depends on, and a demo file. Set up the registry once as described in Shadcn CLI. Comparison is free and installs without an API key.

Manual installation

Install the dependencies and the badge component:

npm install @ui-sdk/core@beta @ui-sdk/react@beta lucide-react
npx shadcn@latest add badge

Copy the source into components/ui/comparison.tsx:

components/ui/comparison.tsx
"use client";
import * as React from "react";import { isRTL } from "@ui-sdk/core";import { Slider, SliderControl, SliderThumb, SliderTrack, createSliderController, type SliderValueChangeDetails,} from "@ui-sdk/react/slider";import { ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon, ChevronsLeftRightIcon, ChevronsUpDownIcon, ChevronUpIcon,} from "lucide-react";
import { Badge } from "@/components/ui/badge";import { cn } from "@/lib/utils";
type ComparisonOrientation = "horizontal" | "vertical";type ComparisonMode = "drag" | "hover";type ComparisonItemPosition = "before" | "after";type ComparisonValueChangeDetails = SliderValueChangeDetails;
type ComparisonContextValue = { orientation: ComparisonOrientation; label: string; handleOnly: boolean;};
const ComparisonContext = React.createContext<ComparisonContextValue | null>( null,);const ComparisonItemContext = React.createContext<ComparisonItemPosition>("after");
function useComparison() { const context = React.useContext(ComparisonContext); if (!context) { throw new Error("Comparison parts must be used inside <Comparison>."); } return context;}
const clamp = (value: number) => Math.min(100, Math.max(0, value));const round = (value: number) => Math.round(value * 100) / 100;
function pointerPosition( event: { clientX: number; clientY: number }, track: HTMLElement, orientation: ComparisonOrientation,) { const rect = track.getBoundingClientRect(); if (orientation === "vertical") { return clamp(((event.clientY - rect.top) / rect.height) * 100); } const ratio = (event.clientX - rect.left) / rect.width; return clamp((isRTL(track) ? 1 - ratio : ratio) * 100);}
type ComparisonProps = Omit< React.ComponentProps<"div">, "defaultValue" | "onChange"> & { value?: number; defaultValue?: number; onValueChange?: (value: number, details: ComparisonValueChangeDetails) => void; onValueCommit?: (value: number) => void; orientation?: ComparisonOrientation; mode?: ComparisonMode; handleOnly?: boolean; step?: number; largeStep?: number; disabled?: boolean; getValueText?: (value: number) => string; "aria-label"?: string;};
function Comparison({ value, defaultValue = 50, onValueChange, onValueCommit, orientation = "horizontal", mode = "drag", handleOnly = false, step = 1, largeStep = 10, disabled = false, getValueText = (position) => `${Math.round(position)}%`, "aria-label": label = "Comparison position", className, style, children, onPointerMove, ...props}: ComparisonProps) { const [uncontrolled, setUncontrolled] = React.useState(defaultValue); const position = clamp(value ?? uncontrolled); const trackRef = React.useRef<HTMLDivElement>(null); const grabOffset = React.useRef(0); const latest = React.useRef(position); const [controller] = React.useState(() => createSliderController<number>());
// ui-sdk's vertical slider grows upward, while "before" sits on top. const toSlider = (next: number) => orientation === "vertical" ? 100 - next : next;
const handleValueChange = ( next: number, details: ComparisonValueChangeDetails, ) => { let nextPosition = toSlider(next); const event = details.event; // The slider snaps pointer moves to `step`; keep pointer input exact so drags stay smooth. if (event && "clientX" in event && trackRef.current) { nextPosition = clamp( pointerPosition(event, trackRef.current, orientation) - grabOffset.current, ); } nextPosition = round(nextPosition); latest.current = nextPosition; onValueChange?.(nextPosition, details); if (details.canceled || value !== undefined) return; setUncontrolled(nextPosition); };
const handlePointerDownCapture = (event: React.PointerEvent) => { const track = trackRef.current; const onHandle = (event.target as Element).closest( "[data-slot=slider-thumb]", ); grabOffset.current = track && onHandle ? pointerPosition(event, track, orientation) - position : 0; };
const handlePointerMove = (event: React.PointerEvent<HTMLDivElement>) => { onPointerMove?.(event); if ( mode !== "hover" || disabled || event.pointerType !== "mouse" || event.buttons !== 0 || !trackRef.current ) { return; } grabOffset.current = 0; const next = pointerPosition(event, trackRef.current, orientation); if (Math.abs(next - position) < 0.01) return; controller.setValue(toSlider(next), { event: event.nativeEvent }); };
return ( <ComparisonContext.Provider value={{ orientation, label, handleOnly }}> <div data-slot="comparison" data-orientation={orientation} data-mode={mode} data-handle-only={handleOnly ? "" : undefined} data-disabled={disabled ? "" : undefined} className={cn( "relative isolate aspect-video w-full touch-none overflow-hidden rounded-xl border bg-muted select-none data-disabled:opacity-50", className, )} style={ { "--comparison-position": `${position}%`, ...style, } as React.CSSProperties } onPointerMove={handlePointerMove} {...props} > <Slider value={toSlider(position)} onValueChange={handleValueChange} onValueCommit={() => onValueCommit?.(latest.current)} orientation={orientation} step={step} largeStep={largeStep} disabled={disabled} controller={controller} format={(next) => getValueText(toSlider(next))} className="absolute inset-0" > <SliderControl onPointerDownCapture={handlePointerDownCapture} className={cn( "absolute inset-0", orientation === "vertical" ? "cursor-ns-resize" : "cursor-ew-resize", (handleOnly || disabled) && "pointer-events-none", )} > <SliderTrack ref={trackRef} className="size-full"> {children} </SliderTrack> </SliderControl> </Slider> </div> </ComparisonContext.Provider> );}
function ComparisonItem({ position, className, ...props}: React.ComponentProps<"div"> & { position: ComparisonItemPosition }) { const { orientation } = useComparison();
return ( <ComparisonItemContext.Provider value={position}> <div data-slot="comparison-item" data-position={position} data-orientation={orientation} className={cn( "pointer-events-none absolute inset-0 overflow-hidden [&_img]:pointer-events-none [&_img]:select-none", position === "before" && (orientation === "vertical" ? "[clip-path:inset(0_0_calc(100%-var(--comparison-position))_0)]" : "[clip-path:inset(0_calc(100%-var(--comparison-position))_0_0)] rtl:[clip-path:inset(0_0_0_calc(100%-var(--comparison-position)))]"), className, )} {...props} /> </ComparisonItemContext.Provider> );}
function ComparisonLabel({ className, ...props}: React.ComponentProps<typeof Badge>) { const { orientation } = useComparison(); const position = React.useContext(ComparisonItemContext);
return ( <Badge data-slot="comparison-label" variant="secondary" className={cn( "absolute top-3 start-3 bg-background/80 text-foreground shadow-sm backdrop-blur-sm", position === "after" && (orientation === "vertical" ? "top-auto bottom-3" : "start-auto end-3"), className, )} {...props} /> );}
type ComparisonHandleVariant = "circle" | "line" | "pill";
function ComparisonHandle({ variant = "circle", className, children, ...props}: Omit< React.ComponentProps<typeof SliderThumb>, "className" | "index" | "children"> & { variant?: ComparisonHandleVariant; className?: string; children?: React.ReactNode;}) { const { orientation, label, handleOnly } = useComparison(); const vertical = orientation === "vertical"; const Icon = vertical ? ChevronsUpDownIcon : ChevronsLeftRightIcon;
return ( <SliderThumb data-variant={variant} aria-label={label} className={cn( "group/handle pointer-events-auto absolute z-10 flex items-center justify-center outline-none", "before:absolute before:bg-background before:shadow-[0_0_0_1px_var(--border)]", vertical ? "h-10 w-full cursor-ns-resize before:inset-x-0 before:top-1/2 before:h-0.5 before:-translate-y-1/2" : "h-full w-10 cursor-ew-resize before:inset-y-0 before:start-1/2 before:w-0.5 before:-translate-x-1/2 rtl:before:translate-x-1/2", handleOnly && "cursor-grab active:cursor-grabbing", className, )} {...props} > <span data-slot="comparison-handle-knob" className={cn( "relative flex shrink-0 items-center justify-center bg-background text-foreground shadow-md ring-1 ring-border transition-[box-shadow,scale] group-has-focus-visible/handle:ring-[3px] group-has-focus-visible/handle:ring-ring/50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", variant === "circle" && "size-9 rounded-full group-active/handle:scale-95", variant === "pill" && cn("rounded-full group-active/handle:scale-95", vertical ? "h-14 w-8 flex-col" : "h-8 w-14"), variant === "line" && cn("rounded-full", vertical ? "h-1.5 w-10" : "h-10 w-1.5"), )} > {variant === "line" ? null : (children ?? (variant === "pill" ? ( vertical ? ( <> <ChevronUpIcon aria-hidden="true" /> <ChevronDownIcon aria-hidden="true" /> </> ) : ( <> <ChevronLeftIcon aria-hidden="true" /> <ChevronRightIcon aria-hidden="true" /> </> ) ) : ( <Icon aria-hidden="true" /> )))} </span> </SliderThumb> );}
export { Comparison, ComparisonHandle, ComparisonItem, ComparisonLabel, type ComparisonHandleVariant, type ComparisonItemPosition, type ComparisonMode, type ComparisonOrientation, type ComparisonProps, type ComparisonValueChangeDetails,};

Usage

import {
  Comparison,
  ComparisonHandle,
  ComparisonItem,
  ComparisonLabel,
} from "@/components/ui/comparison";
<Comparison aria-label="Original and edited photo">
  <ComparisonItem position="after">
    <img src="/after.jpg" alt="Edited photo" className="size-full object-cover" />
  </ComparisonItem>
  <ComparisonItem position="before">
    <img src="/before.jpg" alt="Original photo" className="size-full object-cover" />
  </ComparisonItem>
  <ComparisonHandle />
</Comparison>

Both items fill the whole frame. Render after first: it sits underneath and the before item is clipped to the handle position on top of it, so before shows on the left (or top, when vertical) and after on the right (or bottom). The root has aspect-video by default. Change it with a class like aspect-4/3 or aspect-square.

Position

The value is the handle position in percent, from 0 to 100. It starts at 50. 0 hides the before item and 100 shows it over the whole frame.

<Comparison aria-label="Comparison" defaultValue={30}>...</Comparison>

Examples

Labels

Put a ComparisonLabel inside each item. It's a shadcn/ui Badge that pins itself to the item's corner: top start for before, top end for after, or bottom when vertical.

Edited lake photoAfter
Original lake photoBefore

Vertical

orientation="vertical" splits the frame top and bottom. before is on top.

Snowy mountains at nightAfter
Snowy mountains, brightenedBefore

Hover Mode

With mode="hover", the handle follows a mouse pointer without pressing. Touch and pen still drag.

City skyline in color
City skyline in black and white

Handle Variants

ComparisonHandle has three variants: circle (the default), pill and line.

Forest hills, clear
Forest hills, faded
Forest hills, clear
Forest hills, faded
Forest hills, clear
Forest hills, faded

Handle Only

By default, a press anywhere in the frame moves the handle there. With handleOnly, only dragging the handle itself moves it.

Mountain range in color
Mountain range in black and white

Controlled

Pass value and onValueChange to own the position.

Living room in color
Living room in black and white
50%

Any Content

Items take any children, not only images. Here each item renders text on its own theme.

Dark

After

Light

Before

Disabled

Mountain range in color
Mountain range in black and white

More layouts built with Comparison, such as design and implementation or code diff sliders, are on the Comparison components page.

API Reference

Comparison

The root. It holds the slider that moves the handle, and spreads other props onto its div.

PropTypeDefaultDescription
valuenumberThe handle position, from 0 to 100. Pass it to control the comparison.
defaultValuenumber50The position at first, when uncontrolled.
onValueChange(value, details) => voidRuns on every move of a drag, hover or key. details.reason says why, details.cancel() stops it.
onValueCommit(value) => voidRuns once an interaction ends, like when the pointer lifts.
orientation"horizontal", "vertical""horizontal"Splits the frame left and right, or top and bottom.
mode"drag", "hover""drag"With hover, the handle follows a mouse pointer without pressing.
handleOnlybooleanfalseOnly the handle can be dragged. Presses on the frame do nothing.
stepnumber1How far an arrow key moves the handle, in percent. Pointer moves are not snapped.
largeStepnumber10How far PageUp, PageDown and Shift with an arrow key move it.
disabledbooleanfalseStops every change and dims the frame.
getValueText(value) => string"50%"The value screen readers announce for a position.
aria-labelstring"Comparison position"The handle's accessible name.
classNamestringClasses for the root, like an aspect ratio or a max width.

The root has data-orientation, data-mode, data-handle-only and data-disabled attributes, and sets --comparison-position to the position in percent.

ComparisonItem

One layer. Takes any div props and children.

PropTypeDefaultDescription
position"before", "after"before is clipped to the handle and sits on top. after sits underneath.
classNamestringClasses for the layer.

Images inside an item get pointer-events-none and select-none, so they never start a native image drag.

ComparisonLabel

A shadcn/ui Badge with variant="secondary". It takes every Badge prop and places itself from the item it sits in.

ComparisonHandle

The divider line and the knob. It renders the slider thumb.

PropTypeDefaultDescription
variant"circle", "pill", "line""circle"The knob style. line is a thin bar with no icon.
childrenReactNodechevron iconsReplaces the icon inside the knob. Ignored for line.
classNamestringClasses for the handle.

The handle has a data-variant attribute. The knob has data-slot="comparison-handle-knob".

Keyboard

KeyAction
TabMoves focus to the handle.
ArrowRight, ArrowUpHorizontal: moves the handle right by step. Vertical: moves it up.
ArrowLeft, ArrowDownHorizontal: moves the handle left by step. Vertical: moves it down.
Shift + arrow keyMoves by largeStep.
PageUp, PageDownMoves by largeStep, like ArrowUp and ArrowDown.
HomeHorizontal: moves the handle to the left edge. Vertical: to the bottom edge.
EndHorizontal: moves the handle to the right edge. Vertical: to the top edge.

In right to left layouts, ArrowLeft and ArrowRight swap on a horizontal comparison, and before shows on the right.

Accessibility

  • The handle is a native range input with the slider role, named by the root aria-label. Always pass a label that says what is being compared.
  • Screen readers announce the position from getValueText, by default as a percent like "50%".
  • Give every image in an item its own alt text that describes that version.
  • A disabled comparison can't be focused or moved.

For AI Agents

When to use

  • Showing two versions of the same image or view: edits, retouching, restorations, day and night, light and dark theme.
  • Comparing a design with its implementation, or an old screen with a new one, in the same frame.
  • Any pair of layers that line up and differ in place.

When not to use

  • Two different things side by side, such as two products or plans. Use a grid of Cards or a table.
  • Switching between more than two versions. Use Tabs or a Carousel.
  • Picking a number for a setting. Use a Slider or Range Slider.

Agent notes

  • Import from @/components/ui/comparison. The exports are Comparison, ComparisonItem, ComparisonLabel and ComparisonHandle, plus the types ComparisonProps, ComparisonHandleVariant, ComparisonItemPosition, ComparisonMode, ComparisonOrientation and ComparisonValueChangeDetails.
  • Render the after item first, then the before item, then ComparisonHandle. Items have no z-index, so a later item paints over an earlier one.
  • The position is a percent from 0 to 100, not a pixel offset. onValueChange receives a number, not an array.
  • Give images className="size-full object-cover" so both layers line up. Use the same source with a filter class, or two images of the same size.
  • The frame keeps aspect-video unless you pass another aspect class. Inside a flex parent, also give it a width like w-full or max-w-xl.
  • mode="hover" only follows a mouse. Do not rely on it alone for touch screens: touch still drags.

Resources