Before/after

Compare two images by dragging a divider, with keyboard support.

The same lake graded turquoise under a blue skyA glacial lake below forested mountains in flat, grey tones

Installation

CLI

pnpm dlx shadcn@latest add @riff/before-after

Manual

  1. Copy the component

    Save this as components/ui/before-after.tsx:

    'use client';
    import {
      useId,
      useRef,
      useState,
      type KeyboardEvent,
      type PointerEvent,
      type ReactNode,
    } from 'react';
    import './before-after.css';
    
    export type ComparisonImage = { src: string; alt: string };
    
    const clamp = (value: number) =>
      Number.isNaN(value) ? 50 : Math.min(100, Math.max(0, value));
    
    /**
     * Two images stacked in one frame, split by a divider. Drag anywhere on the
     * frame, or focus the handle and use the arrow keys, Page Up/Down, Home and
     * End.
     */
    export function BeforeAfter({
      before,
      after,
      beforeLabel = 'Before',
      afterLabel = 'After',
      defaultPosition = 50,
      aspectRatio = '3 / 2',
      caption,
    }: {
      before: ComparisonImage;
      after: ComparisonImage;
      beforeLabel?: string;
      afterLabel?: string;
      /** Where the divider starts, as a percentage from the left. */
      defaultPosition?: number;
      /** The frame's ratio; images cover it. */
      aspectRatio?: string;
      caption?: ReactNode;
    }) {
      const captionId = useId();
      const stage = useRef<HTMLDivElement>(null);
      const handle = useRef<HTMLDivElement>(null);
      const [position, setPosition] = useState(() => clamp(defaultPosition));
      const rounded = Math.round(position);
    
      const moveTo = (clientX: number) => {
        const rect = stage.current?.getBoundingClientRect();
        if (rect && rect.width > 0)
          setPosition(clamp(((clientX - rect.left) / rect.width) * 100));
      };
      const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
        if (event.pointerType === 'mouse' && event.button !== 0) return;
        // Keeps the browser from moving focus off the handle focused below.
        event.preventDefault();
        event.currentTarget.setPointerCapture(event.pointerId);
        moveTo(event.clientX);
        handle.current?.focus({ preventScroll: true });
      };
      const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
        if (event.currentTarget.hasPointerCapture(event.pointerId))
          moveTo(event.clientX);
      };
      const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
        const step = event.shiftKey ? 1 : 5;
        const moves: Record<string, (value: number) => number> = {
          ArrowLeft: (value) => value - step,
          ArrowDown: (value) => value - step,
          ArrowRight: (value) => value + step,
          ArrowUp: (value) => value + step,
          PageDown: (value) => value - 10,
          PageUp: (value) => value + 10,
          Home: () => 0,
          End: () => 100,
        };
        const move = moves[event.key];
        if (!move) return;
        event.preventDefault();
        setPosition((value) => clamp(move(value)));
      };
    
      return (
        <figure className="riff-compare">
          <div
            ref={stage}
            role="group"
            aria-label={`${beforeLabel} and ${afterLabel} comparison`}
            aria-describedby={caption ? captionId : undefined}
            className="riff-compare-stage"
            style={{ aspectRatio }}
            onPointerDown={onPointerDown}
            onPointerMove={onPointerMove}
          >
            <img
              className="riff-compare-image"
              src={after.src}
              alt={after.alt}
              draggable={false}
            />
            <img
              className="riff-compare-image"
              data-side="before"
              src={before.src}
              alt={before.alt}
              draggable={false}
              style={{ clipPath: `inset(0 ${100 - position}% 0 0)` }}
            />
            <span
              aria-hidden="true"
              className="riff-compare-label"
              data-side="before"
              data-faded={position < 15 ? '' : undefined}
            >
              {beforeLabel}
            </span>
            <span
              aria-hidden="true"
              className="riff-compare-label"
              data-side="after"
              data-faded={position > 85 ? '' : undefined}
            >
              {afterLabel}
            </span>
            <div className="riff-compare-divider" style={{ left: `${position}%` }}>
              <div
                ref={handle}
                role="slider"
                tabIndex={0}
                aria-label={`Compare ${beforeLabel} and ${afterLabel}`}
                aria-valuemin={0}
                aria-valuemax={100}
                aria-valuenow={rounded}
                aria-valuetext={`${rounded}% ${beforeLabel}, ${100 - rounded}% ${afterLabel}`}
                className="riff-compare-handle"
                onKeyDown={onKeyDown}
              >
                <svg
                  aria-hidden="true"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d="m9 7-5 5 5 5M15 7l5 5-5 5" />
                </svg>
              </div>
            </div>
          </div>
          {caption && (
            <figcaption id={captionId} className="riff-compare-caption">
              {caption}
            </figcaption>
          )}
        </figure>
      );
    }
  2. Copy its styles

    Save this beside it as before-after.css:

    /* Host roles first, system colours after: the component reads your theme
       when it has these properties and stays legible when it does not. */
    @layer components {
      .riff-compare {
        --riff-compare-edge: color-mix(
          in srgb,
          var(--color-border, GrayText),
          var(--color-background, Canvas)
        );
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
        width: 100%;
        margin: 0;
      }
      /* The stage draws its own hairline and clips the images inside it. A
         hairline laid over the images would share their antialiased corner
         curve, and the images would bleed through it; here only the stage's
         background shows at the images' edge, so it matches the hairline. */
      .riff-compare-stage {
        position: relative;
        overflow: hidden;
        border: 1px solid var(--riff-compare-edge);
        border-radius: 0.75rem;
        background-color: var(--riff-compare-edge);
        user-select: none;
        touch-action: pan-y;
        cursor: ew-resize;
      }
      .riff-compare-image {
        position: absolute;
        inset: 0;
        display: block;
        width: 100%;
        height: 100%;
        object-fit: cover;
        pointer-events: none;
      }
      .riff-compare-label {
        position: absolute;
        z-index: 2;
        top: 1rem;
        border: 1px solid var(--riff-compare-edge);
        border-radius: 999px;
        padding: 0.25rem 0.75rem;
        background-color: var(--color-background, Canvas);
        color: var(--color-foreground, CanvasText);
        font-size: 0.75rem;
        font-weight: 500;
        line-height: 1rem;
        pointer-events: none;
        transition: opacity 200ms cubic-bezier(0.4, 0, 0.2, 1);
        &[data-side='before'] {
          left: 1rem;
        }
        &[data-side='after'] {
          right: 1rem;
        }
        &[data-faded] {
          opacity: 0;
        }
      }
      /* A 2px bar in the page colour, with a round handle at its middle. */
      .riff-compare-divider {
        position: absolute;
        z-index: 3;
        top: 0;
        bottom: 0;
        width: 2px;
        translate: -50% 0;
        background-color: var(--color-background, Canvas);
        pointer-events: none;
      }
      .riff-compare-handle {
        position: absolute;
        top: 50%;
        left: 50%;
        display: grid;
        width: 2.5rem;
        height: 2.5rem;
        place-items: center;
        border: 1px solid var(--riff-compare-edge);
        border-radius: 999px;
        background-color: var(--color-background, Canvas);
        box-shadow: 0 1px 3px rgb(0 0 0 / 12%);
        color: var(--color-foreground, CanvasText);
        translate: -50% -50%;
        pointer-events: auto;
        outline: none;
        &:focus-visible {
          box-shadow: 0 0 0 3px
            color-mix(in srgb, var(--color-ring, Highlight) 50%, transparent);
        }
        & > svg {
          width: 1.25rem;
          height: 1.25rem;
        }
      }
      .riff-compare-caption {
        color: var(--color-muted-foreground, GrayText);
        font-size: 0.875rem;
        line-height: 1.4;
      }
      @media (prefers-reduced-motion: reduce) {
        .riff-compare-label {
          transition: none;
        }
      }
      @media (forced-colors: active) {
        .riff-compare-handle:focus-visible {
          outline: 2px solid Highlight;
          outline-offset: 2px;
        }
      }
    }

Usage

import { BeforeAfter } from '@/components/ui/before-after';

<BeforeAfter
  before={{ src: '/old.webp', alt: 'Settings before' }}
  after={{ src: '/new.webp', alt: 'Settings after' }}
/>;

Drag anywhere on the frame, or focus the handle and use the arrow keys (Shift for 1% steps), Page Up and Page Down, Home and End. Both images cover the frame, so give them the same aspect ratio and pass it as aspectRatio.

Props

PropTypeDefaultDescription
before{ src: string; alt: string }The image on the left.
after{ src: string; alt: string }The image on the right.
beforeLabelstring'Before'Its pill label.
afterLabelstring'After'Its pill label.
defaultPositionnumber50Where the divider starts, in percent.
aspectRatiostring'3 / 2'The frame’s ratio.
captionReactNodeText under the frame.