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.
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:
"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.
Vertical
orientation="vertical" splits the frame top and bottom. before is on top.
Hover Mode
With mode="hover", the handle follows a mouse pointer without pressing. Touch and pen still drag.
Handle Variants
ComparisonHandle has three variants: circle (the default), pill and line.
Handle Only
By default, a press anywhere in the frame moves the handle there. With handleOnly, only dragging the handle itself moves it.
Controlled
Pass value and onValueChange to own the position.
Any Content
Items take any children, not only images. Here each item renders text on its own theme.
Dark
AfterLight
BeforeDisabled
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.
| Prop | Type | Default | Description |
|---|---|---|---|
value | number | The handle position, from 0 to 100. Pass it to control the comparison. | |
defaultValue | number | 50 | The position at first, when uncontrolled. |
onValueChange | (value, details) => void | Runs on every move of a drag, hover or key. details.reason says why, details.cancel() stops it. | |
onValueCommit | (value) => void | Runs 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. |
handleOnly | boolean | false | Only the handle can be dragged. Presses on the frame do nothing. |
step | number | 1 | How far an arrow key moves the handle, in percent. Pointer moves are not snapped. |
largeStep | number | 10 | How far PageUp, PageDown and Shift with an arrow key move it. |
disabled | boolean | false | Stops every change and dims the frame. |
getValueText | (value) => string | "50%" | The value screen readers announce for a position. |
aria-label | string | "Comparison position" | The handle's accessible name. |
className | string | Classes 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.
| Prop | Type | Default | Description |
|---|---|---|---|
position | "before", "after" | before is clipped to the handle and sits on top. after sits underneath. | |
className | string | Classes 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.
| Prop | Type | Default | Description |
|---|---|---|---|
variant | "circle", "pill", "line" | "circle" | The knob style. line is a thin bar with no icon. |
children | ReactNode | chevron icons | Replaces the icon inside the knob. Ignored for line. |
className | string | Classes for the handle. |
The handle has a data-variant attribute. The knob has data-slot="comparison-handle-knob".
Keyboard
| Key | Action |
|---|---|
Tab | Moves focus to the handle. |
ArrowRight, ArrowUp | Horizontal: moves the handle right by step. Vertical: moves it up. |
ArrowLeft, ArrowDown | Horizontal: moves the handle left by step. Vertical: moves it down. |
Shift + arrow key | Moves by largeStep. |
PageUp, PageDown | Moves by largeStep, like ArrowUp and ArrowDown. |
Home | Horizontal: moves the handle to the left edge. Vertical: to the bottom edge. |
End | Horizontal: 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
sliderrole, named by the rootaria-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
alttext 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 areComparison,ComparisonItem,ComparisonLabelandComparisonHandle, plus the typesComparisonProps,ComparisonHandleVariant,ComparisonItemPosition,ComparisonMode,ComparisonOrientationandComparisonValueChangeDetails. - Render the
afteritem first, then thebeforeitem, thenComparisonHandle. 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.
onValueChangereceives 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-videounless you pass another aspect class. Inside a flex parent, also give it a width likew-fullormax-w-xl. mode="hover"only follows a mouse. Do not rely on it alone for touch screens: touch still drags.
Resources
- Markdown: /docs/components/comparison.md
- Variants: Comparison components, 10 free examples
- Install:
npx shadcn@latest add @shadcnuikit/comparison1 - MCP: call
get_item_codewithcomparison1from the MCP Server - Full index for agents: llms.txt