# Compare (/docs/compare)





`Compare` stacks two layers in one box: `before` shows from the start edge up to a line, and `after` past it. Dragging the line, or pressing anywhere on the image, moves it. Use it for a restoration, an edit, a redesign: any two images that line up.

```tsx
import { Compare } from '@42-central/ui-react/compare';
import { Image } from '@42-central/ui-react/image';

<Compare
  ratio="3/2"
  before={<Image src={faded} alt="A faded sepia print of the peaks, before restoration" />}
  after={<Image src={restored} alt="The same peaks after restoration, in full color" />}
/>
```

## Playground [#playground]

<story.Playground />

### Full prop browser [#full-prop-browser]

<story.WithControl />

## Controlled [#controlled]

`value` and `onChange` hold the position in your state, from 0 to 100: how much of `before` shows, which is the line's position from the start edge. `onChange` fires on every change, while dragging too. Without `value`, the slider keeps its own, starting at `defaultValue` (50).

<Preview code="&#x22;const [value, setValue] = useState(25);\n\n<Compare value={value} onChange={setValue} ratio=\&#x22;16/9\&#x22; before={…} after={…} />\n<Text>{Math.round(value)}% black and white</Text>\n{[0, 25, 50, 75, 100].map((preset) => (\n  <Button key={preset} onClick={() => setValue(preset)}>{preset}%</Button>\n))}&#x22;">
  <ControlledDemo />
</Preview>

A drag moves the line continuously, so `value` can be fractional (`33.4`). Round it for display.

## Keyboard step [#keyboard-step]

The arrow keys move the line by `step` percent, 5 by default. A keyboard step eases into place over a short transition; a drag never does, so the line stays under the pointer. Home and End jump to the ends, and Page Up and Page Down take the browser's larger step.

<Preview code="`<Compare step={10} defaultValue={20} before={…} after={…} />`">
  <div className="w-120 max-w-full">
    <Compare
      step="10"
      defaultValue="20"
      ratio="16/9"
      before="
      <Image
        src={sized(COMPARE.grayscale, 960)}
        alt=&#x22;A mountain lake at dawn, in black and white&#x22;
        placeholder={BLUR.lake}
      />
    "
      after="
      <Image
        src={sized(COMPARE.color, 960)}
        alt=&#x22;The same lake in color, turquoise water below pine forest&#x22;
        placeholder={BLUR.lake}
      />
    "
    />
  </div>
</Preview>

## Ratio and radius [#ratio-and-radius]

`ratio` fixes the box's shape, and both images fill it, cropped with `object-fit: cover`. Without a `ratio`, the box takes the height of `before`, so give that image a size or a ratio of its own. `radius` rounds the corners on [`Image`](/docs/image)'s scale, `xs` by default; `none` squares them.

<Preview align="block" code="&#x22;<Compare ratio=\&#x22;1/1\&#x22; radius=\&#x22;lg\&#x22; before={…} after={…} />\n<Compare ratio=\&#x22;4/3\&#x22; radius=\&#x22;none\&#x22; before={…} after={…} />&#x22;">
  <div className="flex flex-wrap items-start justify-center gap-6">
    <Compare
      ratio="1/1"
      radius="lg"
      className="w-56"
      before="
      <Image
        src={sized(COMPARE.faded, 448)}
        alt=&#x22;A faded sepia print of snowy peaks above the clouds, before restoration&#x22;
        placeholder={BLUR.mountains}
      />
    "
      after="
      <Image
        src={sized(COMPARE.restored, 448)}
        alt=&#x22;The same peaks after restoration, sharp and in full color&#x22;
        placeholder={BLUR.mountains}
      />
    "
    />

    <Compare
      ratio="4/3"
      radius="none"
      className="w-72"
      before="
      <Image
        src={sized(COMPARE.faded, 576)}
        alt=&#x22;A faded sepia print of snowy peaks above the clouds, before restoration&#x22;
        placeholder={BLUR.mountains}
      />
    "
      after="
      <Image
        src={sized(COMPARE.restored, 576)}
        alt=&#x22;The same peaks after restoration, sharp and in full color&#x22;
        placeholder={BLUR.mountains}
      />
    "
    />
  </div>
</Preview>

The box owns the corners: it clips both layers to its radius and squares the images inside, so their own `radius` doesn't show. Leave them at their default.

### Room for the grip [#room-for-the-grip]

The grip stays centred on the line at every value, so at 0% and 100% it hangs half past the image's edge, about 1.4rem with its focus ring. Compare doesn't clip it. In a full-bleed layout, where the image runs to the edge of the screen, give its container that much inline padding, or the overhang is cut off by the page (or scrolls it sideways) at the ends.

## In a figure [#in-a-figure]

A caption goes in a [`Figure`](/docs/figure), as for any media. Give the figure a width: it hugs its media, and the comparison is fluid.

<Preview align="block" code="&#x22;<Figure className=\&#x22;w-full max-w-120\&#x22; caption=\&#x22;…\&#x22;>\n  <Compare ratio=\&#x22;3/2\&#x22; before={…} after={…} />\n</Figure>&#x22;">
  <div className="flex justify-center">
    <Figure className="w-full max-w-120" caption="The print as we found it, and after restoration. Drag to compare.">
      <Compare
        ratio="3/2"
        before="
        <Image
          src={sized(COMPARE.faded, 960)}
          alt=&#x22;A faded sepia print of snowy peaks above the clouds, before restoration&#x22;
          placeholder={BLUR.mountains}
        />
      "
        after="
        <Image
          src={sized(COMPARE.restored, 960)}
          alt=&#x22;The same peaks after restoration, sharp and in full color&#x22;
          placeholder={BLUR.mountains}
        />
      "
      />
    </Figure>
  </div>
</Preview>

## Right-to-left [#right-to-left]

The direction comes from the locale, as for the kit's other interactive parts. Under an RTL locale, `before` shows from the right edge, the line moves toward the left as the value grows, and <kbd>←</kbd> moves it that way. The value text uses the locale's digits.

<Preview code="&#x22;<IntlProvider locale=\&#x22;ar-EG\&#x22;>\n  <div dir=\&#x22;rtl\&#x22; lang=\&#x22;ar\&#x22;>\n    <Compare\n      ratio=\&#x22;16/9\&#x22;\n      defaultValue={30}\n      translations={{\n        slider: 'مقارنة قبل وبعد',\n        valueText: (percent) => `${percent} بالأبيض والأسود`,\n      }}\n      before={<Image src={grayscale} alt=\&#x22;بحيرة جبلية عند الفجر، بالأبيض والأسود\&#x22; />}\n      after={<Image src={color} alt=\&#x22;البحيرة نفسها بالألوان\&#x22; />}\n    />\n  </div>\n</IntlProvider>&#x22;">
  <DirectionDemo />
</Preview>

`Compare` stamps the locale's `dir` on its root, so the wipe, the native slider and the arrow keys always agree. `<html dir="rtl">` alone leaves it left to right: see [Text direction](/docs/intl#text-direction).

## API [#api]

<TypeTable
  type="{
  before: {
    type: &#x22;ReactNode&#x22;,
    required: true,
    description: &#x22;The original. Shown from the start edge up to the line. Without a ratio, it sets the box's height.&#x22;,
  },
  after: {
    type: &#x22;ReactNode&#x22;,
    required: true,
    description: &#x22;The result. Shown past the line, on the end side.&#x22;,
  },
  value: {
    type: &#x22;number&#x22;,
    description: &#x22;How much of before shows, from 0 to 100: the line's position from the start edge. Controlled. Out-of-range values are clamped.&#x22;,
  },
  defaultValue: {
    type: &#x22;number&#x22;,
    default: &#x22;50&#x22;,
    description: &#x22;The starting value, uncontrolled.&#x22;,
  },
  onChange: {
    type: &#x22;(value: number) => void&#x22;,
    description: &#x22;Every change, while dragging too. A drag gives fractional values.&#x22;,
  },
  step: {
    type: &#x22;number&#x22;,
    default: &#x22;5&#x22;,
    description: &#x22;How far one arrow key moves the line, in percent.&#x22;,
  },
  ratio: {
    type: &#x22;number | `${number}/${number}`&#x22;,
    description: &#x22;Width over height: 16 / 9 or \&#x22;16/9\&#x22;. Without one, before sets the height.&#x22;,
  },
  radius: {
    type: &#x22;'none' | 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'full'&#x22;,
    default: &#x22;'xs'&#x22;,
    description: &#x22;Corner radius, on Image's scale. Both layers are clipped to it.&#x22;,
  },
  translations: {
    type: &#x22;{ slider?, valueText? }&#x22;,
    description: &#x22;The slider's name, and its announced value. See [Internationalization](#internationalization).&#x22;,
  },
  className: {
    type: &#x22;string&#x22;,
    description: &#x22;Applies to the root. It's a block: size it here.&#x22;,
  },
  classNames: {
    type: &#x22;{ root?, before?, after?, line?, handle?, input? }&#x22;,
    description: &#x22;Per-part class overrides. handle is the round grip; input is the transparent native range.&#x22;,
  },
  testId: {
    type: &#x22;string&#x22;,
    description: &#x22;Renders as data-testid on the native range input. See [Testing](/docs/testing).&#x22;,
  },
}"
/>

Every other `<div>` attribute is passed to the root. No `asChild`: the root renders both layers, the slider and the handle.

## Accessibility [#accessibility]

* **A native slider.** The control is an `<input type="range">` laid over the whole image at zero opacity. Screen readers announce it as a slider, named by `translations.slider`, with `aria-valuetext` from `translations.valueText` ("30% before").

* **Keyboard.**

  | Key                                       | Action                                                     |
  | ----------------------------------------- | ---------------------------------------------------------- |
  | <kbd>Tab</kbd>                            | Focuses the slider. The ring goes around the grip.         |
  | <kbd>→</kbd> <kbd>↑</kbd>                 | Shows more of `before`, by `step`. <kbd>←</kbd> under RTL. |
  | <kbd>←</kbd> <kbd>↓</kbd>                 | Shows more of `after`, by `step`. <kbd>→</kbd> under RTL.  |
  | <kbd>Home</kbd> / <kbd>End</kbd>          | All `after` / all `before`.                                |
  | <kbd>Page Up</kbd> / <kbd>Page Down</kbd> | The browser's larger step.                                 |

* **Pointer and touch.** Press anywhere on the image to move the line there, then drag. On touch, a horizontal drag moves the line and a vertical one still scrolls the page. The whole image is the hit area.

* **Visible focus.** The kit's focus ring goes around the grip, which stays centred on the line. At the ends the grip and its ring hang half past the image's edge; nothing in Compare clips them, so the ring is never cut. Leave [room for the grip](#room-for-the-grip) in full-bleed layouts.

* **Name the images.** Each image keeps its own `alt`, so say which side is which in it: "The fresco before restoration", "The fresco after restoration". The slider's name says what is being compared; the alts say what each layer shows.

* **Reduced motion.** A keyboard step eases over 150ms; under `prefers-reduced-motion` it jumps. A drag never animates.

* **Forced colors.** The line and the grip switch to system colors in Windows High Contrast, and the grip gets the system focus outline.

* **Right-to-left.** Everything is placed with logical properties, and the direction comes from the locale. See [Right-to-left](#right-to-left).

## Internationalization [#internationalization]

`translations` holds the two strings the slider announces. Both are optional; a partial override keeps the other English default.

| Key         | Default                                |                                                                                                                     |
| ----------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `slider`    | `"Before and after comparison"`        | The slider's accessible name.                                                                                       |
| `valueText` | `` (percent) => `${percent} before` `` | Its announced value. `percent` is already formatted for the locale: `"30%"`, `"30 %"` in French, `"٣٠٪"` in Arabic. |

```tsx
<Compare
  translations={{
    slider: t('compare.label'),             // "Avant et après restauration"
    valueText: (percent) => t('compare.value', { percent }), // "30 % avant"
  }}
  before={<Image src={original} alt={t('fresco.before')} />}
  after={<Image src={restored} alt={t('fresco.after')} />}
/>
```

The percentage is formatted with `Intl.NumberFormat` in the locale from [`IntlProvider`](/docs/intl). The images' `alt` text is your content: translate it with the rest of the page.
