日本語

How to Build a Before/After Image Comparison Slider in React

​​React​Accessibility,CSS,Playwright,Pointer Events,TypeScript

Place two images at the same position, hide the right side of the top image with the CSS clip-path, and you get a view where a divider you drag left and right compares the two. In React, the only state is the divider position (a % of the width). The images themselves keep their size, so the two pictures stay aligned wherever the divider moves. This works well when you want readers to compare a before and after pair inside a single frame.

Here I built ImageCompare, which moves the divider by dragging the handle, by clicking the image, or with the arrow keys. I also compare it with an approach that changes the width of a wrapping element, and I check what happens when setPointerCapture() or preventDefault() is not called.

Note

The test environment was Ubuntu 24.04, Node.js 22.22.0, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, and Playwright 1.63.0, and checked the behavior by operating the mouse and keyboard with Playwright. The images were not photographs. They were 1200×800 PNGs drawn with Pillow, one in color and one in monochrome. Both images are the same size, and I did not test overlaying images of different sizes. I did not test touch input, Firefox, Safari, mobile browsers, or reading with a screen reader.

Dragging the handle to the right widens the monochrome area. Clicking the left part of the image moves the divider to that spot. Pressing the → key five times moves the divider gradually to the right
The divider moving through three operations. Only the changed numbers are shown in pink. The cursor and operation indicators are overlays added for the GIF.

Overlay two images and cut the top one with clip-path

ImageCompare takes the image underneath (after) and the image on top (before). The divider position position is a % where 0 is the left edge and 100 is the right edge.

tsx
import { useRef, useState } from 'react';
import type { KeyboardEvent, PointerEvent } from 'react';

type Props = {
  before: string;
  after: string;
  beforeAlt: string;
  afterAlt: string;
  // Initial position of the divider (% from the left edge)
  initial?: number;
  onChange?: (position: number) => void;
};

const clamp = (n: number, min: number, max: number) => Math.min(Math.max(n, min), max);

export function ImageCompare({ before, after, beforeAlt, afterAlt, initial = 50, onChange }: Props) {
  // Store the divider position as a % of the width (it still points to the same spot when the screen width changes)
  const [position, setPosition] = useState(initial);
  const rootRef = useRef<HTMLDivElement>(null);
  const handleRef = useRef<HTMLDivElement>(null);
  const dragging = useRef(false);

  function update(next: number) {
    const p = clamp(next, 0, 100);
    setPosition(p);
    onChange?.(p);
  }

  // Convert the pointer position to a % of the width
  function toPercent(e: PointerEvent) {
    const r = rootRef.current!.getBoundingClientRect();
    return ((e.clientX - r.left) / r.width) * 100;
  }

  function handlePointerDown(e: PointerEvent<HTMLDivElement>) {
    if (e.button !== 0) return;
    dragging.current = true;
    // Keep sending events to this element even if the pointer leaves the image, until it is released
    e.currentTarget.setPointerCapture(e.pointerId);
    // Move the divider to the pressed spot, and focus the handle so the arrow keys can move it next
    update(toPercent(e));
    handleRef.current?.focus();
    e.preventDefault();
  }

  function handlePointerMove(e: PointerEvent<HTMLDivElement>) {
    if (dragging.current) update(toPercent(e));
  }

  function handlePointerUp() {
    dragging.current = false;
  }

  // Arrow keys move by 1%, or by 10% with Shift. Home and End jump to the ends
  function handleKeyDown(e: KeyboardEvent) {
    const step = e.shiftKey ? 10 : 1;
    const next = {
      ArrowLeft: position - step,
      ArrowDown: position - step,
      ArrowRight: position + step,
      ArrowUp: position + step,
      Home: 0,
      End: 100,
    }[e.key];
    if (next === undefined) return;
    e.preventDefault();
    update(next);
  }

  const rounded = Math.round(position);

  return (
    <div
      ref={rootRef}
      className="compare"
      onPointerDown={handlePointerDown}
      onPointerMove={handlePointerMove}
      onPointerUp={handlePointerUp}
      onPointerCancel={handlePointerUp}
    >
      {/* The image underneath. Its size becomes the size of the whole component */}
      <img src={after} alt={afterAlt} />
      {/* The image on top. Its right side is hidden with clip-path, so only the part left of the divider is shown */}
      <img
        className="compare-before"
        src={before}
        alt={beforeAlt}
        style={{ clipPath: `inset(0 ${100 - position}% 0 0)` }}
      />
      <div
        ref={handleRef}
        className="compare-handle"
        role="slider"
        tabIndex={0}
        aria-label="2枚の画像の境目"
        aria-valuemin={0}
        aria-valuemax={100}
        aria-valuenow={rounded}
        aria-valuetext={`左の画像を ${rounded}% 表示`}
        onKeyDown={handleKeyDown}
        style={{ left: `${position}%` }}
      />
    </div>
  );
}

The inset() function on the top image creates a rectangle inset from the top, right, bottom, and left edges by the amounts given. When you pass it to clip-path, nothing outside that rectangle is painted. Because only the right side is cut by 100 - position %, only the part to the left of the divider is visible.

Whether the user is dragging is kept in a ref created with useRef. Since this value is not used for rendering, writing to a ref does not trigger a re-render.

The look is done in CSS. The top image is placed exactly over the bottom one with position: absolute and inset: 0. The vertical divider line and the round handle are drawn with .compare-handle and its ::after.

css
.compare {
  position: relative;
  max-width: 600px;
  overflow: hidden;
  cursor: ew-resize;
  /* Keep the page from scrolling sideways when dragging with touch */
  touch-action: pan-y;
  user-select: none;
}
.compare img { display: block; width: 100%; height: auto; }
/* Place the top image at exactly the same position and size as the bottom image */
.compare .compare-before {
  position: absolute;
  inset: 0;
  height: 100%;
  object-fit: cover;
}

/* The vertical divider line and the round handle in the middle */
.compare-handle {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 2px;
  margin-left: -1px;
  background: #fff;
}
.compare-handle::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 32px;
  height: 32px;
  margin: -16px 0 0 -16px;
  border: 2px solid #fff;
  border-radius: 50%;
  background: #067a98;
  box-sizing: border-box;
}
.compare-handle:focus-visible { outline: none; }
.compare-handle:focus-visible::after { box-shadow: 0 0 0 3px #00c8e8; }

touch-action: pan-y tells the browser to handle only vertical scrolling by touch (see the touch-action reference). A sideways touch is not treated as scrolling and should arrive as a pointer event. I did not test this with touch input.

On the using side, I display the position received through onChange.

tsx
import { useState } from 'react';
import { ImageCompare } from './ImageCompare';

export function App() {
  const [position, setPosition] = useState(50);
  return (
    <main>
      <ImageCompare
        before="before.png"
        after="after.png"
        beforeAlt="モノクロの風景"
        afterAlt="カラーの風景"
        onChange={setPosition}
      />
      <p className="compare-info">モノクロの範囲:{Math.round(position)}%</p>
    </main>
  );
}

Check pixel by pixel that the divider is really at that position

I displayed the image at 600×400, took a screenshot, and scanned one row of pixels from the left. I counted how many pixels from the left stay monochrome (where the difference between R, G, and B is 2 or less). The y=100 in the output is the row position in the original image, which is 800 px high. I hid the white divider line only while taking the screenshot.

text
画面上の画像の大きさ: 600×400
モノクロの範囲:50% / aria-valuenow 50
y=100 の行: 幅 600px のうち、左から 300px がモノクロ(それより右にモノクロの画素: 0)

画像の左から 25% の所をクリック: モノクロの範囲:25% / aria-valuenow 25
y=100 の行: 幅 600px のうち、左から 150px がモノクロ(それより右にモノクロの画素: 0)
つまみを 80% の所までドラッグ中: モノクロの範囲:80% / aria-valuenow 80
y=600 の行: 幅 600px のうち、左から 480px がモノクロ(それより右にモノクロの画素: 0)

At 50% the monochrome area was 300 px, at 25% it was 150 px, and at 80% it was 480 px. The divider was exactly at the specified position.

When I changed the screen width from 640 px to 360 px, the divider stayed at the same proportion. This is because the position is stored as a % and not as px.

text
幅 640px: モノクロの範囲:30% / aria-valuenow 30 / 画像の幅 600px、縦線の中心は左から 30.0% / y=100 の行: 幅 600px のうち、左から 180px がモノクロ(それより右にモノクロの画素: 0)
幅 360px に変更: モノクロの範囲:30% / aria-valuenow 30 / 画像の幅 320px、縦線の中心は左から 30.0% / y=100 の行: 幅 320px のうち、左から 96px がモノクロ(それより右にモノクロの画素: 0)

Wrapping approach that changes the width shrinks the top image

Without clip-path, you could also wrap the top image in an element with overflow: hidden and set that element's width to the divider position. For comparison, I built WidthCompare, which fixes the divider at 30%.

tsx
// For comparison: instead of clip-path, change the width of the element that wraps the top image
import { useState } from 'react';

export function WidthCompare({ before, after }: { before: string; after: string }) {
  const [position] = useState(30);
  return (
    <div className="compare">
      <img src={after} alt="カラーの風景" />
      <div className="width-wrap" style={{ position: 'absolute', inset: 0, width: `${position}%`, overflow: 'hidden' }}>
        <img className="width-before" src={before} alt="モノクロの風景" />
      </div>
    </div>
  );
}
text
画像全体: 600×400 / 上の画像: 180×120
y=100 の行: 幅 600px のうち、左から 180px がモノクロ(それより右にモノクロの画素: 0)
clip-path の場合の上の画像: 600×400

The monochrome area was 180 px, the same as with clip-path at 30%, but the top image shrank to 180×120. The image has width: 100%, so it was scaled down to fit the width of the wrapping element. With clip-path, the top image stays at 600×400, and only the visible area changes.

The top shows the clip-path version, where the right side is hidden and the picture lines up across the divider. The bottom shows the wrapper version with width set to 30%, where the monochrome landscape is shrunk and overlaid in the upper left, so the picture no longer lines up
The two approaches with the divider at 30%. With the bottom approach, the top image shrinks and the picture is misaligned

To keep the wrapping approach from shrinking the image, you need to add a separate rule that makes the inner image the same width as the whole component. With clip-path, you do not need to touch the image size.

Handle drag and click together on the parent element

Pointer events are received by .compare, which wraps the whole component, not by the handle. This way, whether you grab the handle or press another part of the image, the divider moves to the pressed spot and dragging continues. I pressed at 10% (in the upper part of the image), away from the handle, and dragged to 60%. The divider ended at 60%.

The setPointerCapture() call in the press handler keeps sending that pointer's events to the element that called it until the button is released. I compared this with the case where it is not called (using a page where setPointerCapture is replaced with a function that does nothing).

text
あり: 50% の所から画像の右の外までドラッグして離す: モノクロの範囲:100% / aria-valuenow 100 / 押さずに 20% の所へ戻る: モノクロの範囲:100% / aria-valuenow 100
なし: 50% の所から画像の右の外までドラッグして離す: モノクロの範囲:98% / aria-valuenow 98 / 押さずに 20% の所へ戻る: モノクロの範囲:20% / aria-valuenow 20

Without the call, events stopped arriving once the pointer left the image, and the divider stopped at 98%. The 98% is the last position that landed inside the image when I moved in 8% steps with Playwright. It never reached the 100% edge. In addition, the release outside the image was not reported, so when the pointer came back over the image without a button pressed, the divider followed it. With the call, dragging outside the image stopped the divider at the 100% edge, and it did not move after release.

Call preventDefault() in pointerdown to keep focus on the handle

After pressing the image, I call focus() on the handle inside handlePointerDown, so that the arrow keys can make fine adjustments right after. However, focus did not stay on the handle with that alone. This is the result compared with a page where preventDefault() is replaced with a function that does nothing.

text
あり: 25% の所をクリック → フォーカス: compare-handle / mousedown: なし / 続けて → を2回: モノクロの範囲:27% / aria-valuenow 27
なし: 25% の所をクリック → フォーカス: BODY / mousedown: mousedown / 続けて → を2回: モノクロの範囲:25% / aria-valuenow 25

Without preventDefault(), a mousedown event arrived after pointerdown, and after the click, focus was on body. As a result, pressing the → key did not move the divider. To keep pages that rely only on the mouse working, browsers may also send mouse events (such as mousedown) that correspond to pointer actions. Calling preventDefault() in pointerdown can stop some of those from being sent (see the compatibility section on mouse events in MDN's Pointer Events page). With the call, mousedown did not arrive, and focus stayed on the handle.

Attributes for the keyboard and screen readers

The handle div has the slider role, along with aria-valuemin, aria-valuemax, and aria-valuenow. MDN recommends using <input type="range"> where possible. I used a div here because I wanted to draw the handle freely over the image. If you build a slider without an input element, make it focusable with tabindex and update aria-valuenow every time the value changes. A number alone does not make the meaning clear, so I also pass a sentence with aria-valuetext, such as "Showing 50% of the left image". I confirmed that Playwright's getByRole('slider', { name: '2枚の画像の境目' }) finds the handle, but I did not test how a real screen reader reads it.

For keys, I followed the slider operations described in MDN. The arrow keys move the divider by 1%, and Home and End move it to the ends. Moving by 10% with Shift and an arrow key is a behavior I chose for this article.

text
50% の所をクリックしてから → を3回: モノクロの範囲:53% / aria-valuenow 53
Shift + ←: モノクロの範囲:43% / aria-valuenow 43
End: モノクロの範囲:100% / aria-valuenow 100
Home: モノクロの範囲:0% / aria-valuenow 0
さらに ←: モノクロの範囲:0% / aria-valuenow 0
Tab で離れて Shift+Tab で戻ったときのフォーカス: compare-handle

After pressing Home to set 0%, pressing ← keeps it at 0%, because clamp limits the value to the range 0 to 100. When I moved away with Tab and came back with Shift+Tab, focus returned to the handle.

​Posted by 86