# Gallery (/docs/gallery)





`Gallery` lays out a list of photos, each one an [`Image`](/docs/image). Give it `data` with each photo's `width` and `height`, and pick a `layout`. Nothing is measured in the browser: the layout comes from CSS and the photos' sizes, so it's correct in the server HTML and doesn't shift when the page hydrates.

```tsx
import { Gallery } from '@42-central/ui-react/gallery';

const photos = [
  { src: '/photos/lake.jpg', alt: 'A mountain lake at dawn', width: 1600, height: 1067 },
  { src: '/photos/falls.jpg', alt: 'A waterfall under a stone bridge', width: 1067, height: 1600 },
  // …
];

<Gallery data={photos} layout="justified" loader={cdnLoader} />
```

## Playground [#playground]

<story.Playground />

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

<story.WithControl />

## Grid [#grid]

The default. As many tracks as fit at `min` pixels wide (160 by default), with every cell cropped to `ratio` (square by default). A track is never wider than the gallery, so a gallery narrower than `min` shows one column instead of overflowing.

<Preview align="block" code="`<Gallery data={photos} min={160} ratio={1} loader={unsplash} />`">
  <LayoutDemo layout="grid" count="12" />
</Preview>

Change the cell shape with `ratio`:

<Preview align="block" code="`<Gallery data={photos} min={220} ratio=&#x22;16/9&#x22; loader={unsplash} />`">
  <LayoutDemo layout="grid" min="220" ratio="16/9" count="8" />
</Preview>

## Masonry [#masonry]

`columns` columns of whole, uncropped photos. Each photo goes to the column that is shortest so far, which keeps the columns' heights close.

<Preview align="block" code="`<Gallery data={photos} layout=&#x22;masonry&#x22; columns={3} loader={unsplash} />`">
  <LayoutDemo layout="masonry" columns="3" />
</Preview>

The photos sit in their columns in the DOM, so the reading order and the tab order run down the first column, then the second, and so on. Each item keeps its position in `data` as `data-index`, and that's the index the gallery opens. See [Accessibility](#accessibility).

### Responsive columns [#responsive-columns]

`columns` is a fixed count, or one count per breakpoint: `{ base: 2, md: 3, lg: 4 }`. The breakpoints are the kit's (`xs` 480, `sm` 640, `md` 768, `lg` 1024, `xl` 1280, `2xl` 1536px), matched against **the gallery's own width**, not the viewport's, so a gallery in a sidebar gets its own count. Or give `min`, the narrowest a column may get, and the gallery fits as many columns as it can, the way a grid fits its tracks:

<Preview align="block" code="&#x22;<Gallery data={photos} layout=\&#x22;masonry\&#x22; columns={{ base: 2, xs: 3 }} />\n<Gallery data={photos} layout=\&#x22;masonry\&#x22; min={220} columns={2} />&#x22;">
  <LayoutDemo layout="masonry" columns="{ base: 2, xs: 3 }" count="12" />
</Preview>

This one has 2 columns below 480px of gallery width and 3 from there, whatever the viewport: narrow the window and it switches when the docs column does.

Both need the gallery's width, which only the browser knows, so they're the one part of `Gallery` that measures. &#x2A;*The server HTML and the first paint use `columns`** (the map's `base`, or 1 without one), then an observer measures the gallery and switches to the right count. Choose that starting count for your most common width, such as `base` for a mobile-first page, so most visitors see no change. With `min`, `columns` is only that starting count. A plain number needs no measuring: it's exact in the server HTML, and no observer is mounted.

Rendering one column set per breakpoint and hiding the others with CSS would avoid the switch, but every photo would then exist several times: as duplicate list items, duplicate test ids and duplicate tiles registered for the same index. One set and one switch is the simpler trade.

## Justified [#justified]

Rows that fill the width, with every photo whole and uncropped, as on Flickr or Google Photos. On a wide gallery the rows are `rowHeight` pixels high (200 by default); on a narrower one they get shorter, so a phone still fits about three photos across.

<Preview align="block" code="`<Gallery data={photos} layout=&#x22;justified&#x22; loader={unsplash} />`">
  <LayoutDemo layout="justified" />
</Preview>

It's flexbox and CSS, with no JavaScript and nothing measured:

```css
/* The gallery: an inline-size container, so 25cqi is a quarter of its width */
--row: clamp(96px, 25cqi, rowHeight);

/* Each item, for a photo of aspect ratio r */
flex: r 1 calc(var(--row) * r);
max-width: calc(var(--row) * r * (1 + tolerance));
aspect-ratio: r;
```

* **The row height follows the gallery's width.** Three 4:3 photos side by side are four row heights wide, so a row height of a quarter of the width fits about three average photos a row. It stops at `rowHeight` on a wide gallery, and never goes under 96px, so thumbnails stay easy to tap in a narrow one.
* **Rows fill the width.** Each photo starts at its width at that height and grows in proportion to its aspect ratio, so every photo on a row grows to the same height.
* **A row that can't be filled stops early.** It grows by at most `tolerance` (25% by default), then ends short of the edge instead of blowing up its photos. That's always the last row, and sometimes a row whose next photo is too wide to fit. The more photos fit on a row, the smaller that gap, which is what scaling the row height is for.

The gallery takes its width from its parent, never from its photos. Inside a flex row, give it `flex-1` or a width.

## Captions [#captions]

Give an item a `caption` to show it over the bottom of its photo, on [`Figure`](/docs/figure)'s overlay scrim. It keeps white text above 4.5:1 contrast over any photo, in both themes.

<Preview align="block" code="`<Gallery data={photos.map((p) => ({ ...p, caption: p.place }))} ratio=&#x22;4/3&#x22; />`">
  <CaptionsDemo />
</Preview>

Keep them to a line: a long caption covers the photo it describes.

## Opening a photo [#opening-a-photo]

`Gallery` doesn't open anything by itself. It reads the **open-index seam**: when an `OpenIndexProvider` is above it, every tile becomes a button that calls `open(index, element)` with its position in `data` and its own element. A lightbox provides it, or your own code does, to open a route or a side panel. With no provider, the tiles stay plain images, and nothing in the gallery is focusable.

This demo's provider just logs what it gets. Click a photo, or tab to one and press <kbd>Enter</kbd>:

<Preview align="block" code="&#x22;import { OpenIndexProvider, type OpenIndex } from '@42-central/ui-react';\n\nconst tiles = new Map<number, HTMLElement>();\nconst seam: OpenIndex = {\n  open: (index, from) => console.log(index, from.getBoundingClientRect()),\n  // Each tile registers while it's mounted. A tile that moves (masonry\n  // switching its column count) registers its new element first, so only\n  // remove the entry if it's still this element.\n  register: (index, element) => {\n    tiles.set(index, element);\n    return () => {\n      if (tiles.get(index) === element) tiles.delete(index);\n    };\n  },\n};\n\n<OpenIndexProvider value={seam}>\n  <Gallery data={photos} />\n</OpenIndexProvider>&#x22;">
  <OpenIndexDemo />
</Preview>

`register` is how a viewer gets back to the right tile. Each tile registers its element under its index, so a lightbox opened on photo 2 and navigated to photo 5 can return focus, and animate, to photo 5's tile when it closes. Keep the provider's `value` stable (`useMemo`): every tile registers again when it changes.

## Responsive [#responsive]

Every layout follows the gallery's own width. Drag the slider: the grid fits fewer tracks, justified rows get shorter, and masonry fits fewer 140px-wide columns.

<Preview align="block" code="&#x22;<Gallery data={photos} layout=\&#x22;grid\&#x22; min={120} />\n<Gallery data={photos} layout=\&#x22;justified\&#x22; />\n<Gallery data={photos} layout=\&#x22;masonry\&#x22; min={140} columns={2} />&#x22;">
  <ResponsiveDemo />
</Preview>

Each layout also gets a default `sizes`, so a `loader` srcset fetches about the right width: twice `min` for a grid (a track never reaches it), one column's share of the viewport for masonry, and each photo's maximum width for justified rows. Pass `sizes` to override it for every photo.

## Spacing and radius [#spacing-and-radius]

`spacing` sets the gap on the kit's size scale (`md`, 8px, by default; `none` for a flush wall). `radius` rounds every photo like `Image` does, `xs` by default; `"none"` squares them.

<Preview align="block" code="&#x22;<Gallery data={photos} spacing=\&#x22;none\&#x22; radius=\&#x22;none\&#x22; />\n<Gallery data={photos} spacing=\&#x22;xl\&#x22; radius=\&#x22;lg\&#x22; />&#x22;">
  <div className="flex w-full flex-col gap-6">
    <LayoutDemo layout="grid" count="6" min="100" spacing="none" radius="none" />

    <LayoutDemo layout="grid" count="6" min="100" spacing="xl" radius="lg" />
  </div>
</Preview>

## Custom tiles [#custom-tiles]

`renderItem(item, index, image)` replaces a tile's media. `image` is the `Image` the gallery would have rendered, so you can wrap it, add a badge over it, or swap it for something else. The caption and the open button stay the gallery's. Under a provider, the media sits inside a `<button>`, so return phrasing content only: an `Image`, `<span>`s, no `<div>`s or links.

```tsx
<Gallery
  data={photos}
  renderItem={(item, index, image) => (
    <span className="relative block size-full">
      {image}
      {item.video && <Badge className="absolute end-2 top-2">Video</Badge>}
    </span>
  )}
/>
```

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

Every layout uses flexbox or grid with logical properties, so it follows the direction: rows and the grid fill from the right, masonry's first column is on the right, and captions are start-aligned. The page's direction toggle flips every demo on this page; this one is right-to-left with Arabic alt text, and its last two photos are decorative, so their buttons take the translated `openLabel`, with Arabic numerals from the locale.

<Preview align="block" code="&#x22;<IntlProvider locale=\&#x22;ar-EG\&#x22;>\n  <div dir=\&#x22;rtl\&#x22; lang=\&#x22;ar\&#x22;>\n    <Gallery\n      data={photos}\n      layout=\&#x22;justified\&#x22;\n      translations={{ openLabel: (position, count) => `فتح الصورة ${position} من ${count}` }}\n    />\n  </div>\n</IntlProvider>&#x22;">
  <DirectionDemo />
</Preview>

## API [#api]

<TypeTable
  type="{
  data: {
    type: &#x22;GalleryItem[]&#x22;,
    required: true,
    description: &#x22;The photos, in order. Each one's width and height lay the gallery out.&#x22;,
  },
  layout: {
    type: &#x22;'grid' | 'masonry' | 'justified'&#x22;,
    default: &#x22;'grid'&#x22;,
    description: &#x22;Cropped cells, uncropped columns, or uncropped rows.&#x22;,
  },
  spacing: {
    type: &#x22;'none' | 'xs' | 'sm' | 'md' | 'lg' | 'xl'&#x22;,
    default: &#x22;'md'&#x22;,
    description: &#x22;The gap between photos: 0, 4, 6, 8, 12 or 16px.&#x22;,
  },
  radius: {
    type: &#x22;'none' | 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'full'&#x22;,
    default: &#x22;'xs'&#x22;,
    description: &#x22;Corner radius of every photo, on Image's scale.&#x22;,
  },
  loader: {
    type: &#x22;ImageLoader&#x22;,
    description: &#x22;Forwarded to every photo's Image, for a srcset from your CDN.&#x22;,
  },
  sizes: {
    type: &#x22;string&#x22;,
    description: &#x22;Overrides the per-layout default sizes for every photo.&#x22;,
  },
  min: {
    type: &#x22;number&#x22;,
    description: &#x22;The narrowest a column gets, in px. Grid: auto-fills tracks (160 by default). Masonry: fits as many columns as the measured width allows, and wins over columns once measured.&#x22;,
  },
  ratio: {
    type: &#x22;number | `${number}/${number}`&#x22;,
    default: &#x22;1&#x22;,
    description: &#x22;Grid: the cell's aspect ratio. Photos are cropped to it.&#x22;,
  },
  columns: {
    type: &#x22;number | { base?, xs?, sm?, md?, lg?, xl?, '2xl'? }&#x22;,
    default: &#x22;3&#x22;,
    description: &#x22;Masonry: the column count, or one per breakpoint of the gallery's own width. A map, or min, is measured on the client; the server renders this count, or base.&#x22;,
  },
  rowHeight: {
    type: &#x22;number&#x22;,
    default: &#x22;200&#x22;,
    description: &#x22;Justified: the row height on a wide gallery, in px. Narrower galleries get shorter rows, down to 96px.&#x22;,
  },
  tolerance: {
    type: &#x22;number&#x22;,
    default: &#x22;0.25&#x22;,
    description: &#x22;Justified: how far past rowHeight a row that can't fill the width may grow.&#x22;,
  },
  renderItem: {
    type: &#x22;(item, index, image) => ReactNode&#x22;,
    description: &#x22;Replaces a tile's media; image is the default Image. Captions and the button stay.&#x22;,
  },
  translations: {
    type: &#x22;GalleryTranslations&#x22;,
    description: &#x22;See Internationalization.&#x22;,
  },
  classNames: {
    type: &#x22;{ root?, item?, image?, caption? }&#x22;,
    description: &#x22;Per-part classes. image applies to each Image's root.&#x22;,
  },
  testId: {
    type: &#x22;string&#x22;,
    description: &#x22;Renders as data-testid on the list root. See [Testing](/docs/testing).&#x22;,
  },
}"
/>

Every other `<div>` attribute goes to the root, `aria-label` included. No `asChild`.

### GalleryItem [#galleryitem]

<TypeTable
  type="{
  src: { type: &#x22;string&#x22;, description: &#x22;The photo's URL, passed to loader.&#x22; },
  alt: { type: &#x22;string&#x22;, required: true, description: &#x22;Describes the photo. \&#x22;\&#x22; for a decorative one.&#x22; },
  width: { type: &#x22;number&#x22;, required: true, description: &#x22;Intrinsic width, in px.&#x22; },
  height: { type: &#x22;number&#x22;, required: true, description: &#x22;Intrinsic height, in px.&#x22; },
  caption: { type: &#x22;ReactNode&#x22;, description: &#x22;Shown over the photo's bottom edge.&#x22; },
  placeholder: { type: &#x22;string&#x22;, description: &#x22;A CSS color or a tiny data: URI, as on Image.&#x22; },
  &#x22;quality, fallback, fit, position&#x22;: { type: &#x22;…&#x22;, description: &#x22;Passed to the photo's Image.&#x22; },
  key: { type: &#x22;string&#x22;, description: &#x22;A stable React key. Defaults to the index.&#x22; },
  testId: { type: &#x22;string&#x22;, description: &#x22;Renders as data-testid on the item.&#x22; },
}"
/>

### OpenIndexProvider [#openindexprovider]

<TypeTable
  type="{
  value: {
    type: &#x22;{ open(index, from): void; register(index, element, reveal?): () => void }&#x22;,
    required: true,
    description: &#x22;open: a tile was activated, with its element. register: a tile mounted; return its unregister. reveal, when an item passes one (a Carousel slide), scrolls it into view: call it before measuring or focusing the element.&#x22;,
  },
}"
/>

`useOpenIndex()` reads the nearest provider (`undefined` without one), and `useOpenIndexTrigger(index)` gives your own element the same opener props as a gallery tile. Both come from `@42-central/ui-react`; see [useOpenIndex](/docs/hooks/use-open-index) for a demo and their full API.

## Accessibility [#accessibility]

* **A list.** The root has `role="list"` and every photo `role="listitem"`, so screen readers announce how many photos there are. Name it with `aria-label` when the page has more than one.
* **Masonry reading order.** Masonry puts its items in column containers (`role="none"`), which keep them direct items of the list. The reading order and the tab order run down each column in turn, which is not left to right across the rows. When order matters, as in a timeline, use `grid` or `justified`, which keep `data`'s order.
* **Masonry column changes.** When a measured masonry (a breakpoint map or `min`) switches its column count, its tiles move to new columns. A tile that had keyboard focus keeps it: focus follows the tile to its new place.
* **Buttons only when something opens.** Under an `OpenIndexProvider`, each tile is a real `<button>` with `aria-haspopup="dialog"`, named by its photo's `alt`. With `alt=""` it's named by `translations.openLabel` instead ("Open image 3 of 12"). With no provider, nothing is focusable.
* **Keyboard.** <kbd>Tab</kbd> moves through the tiles; <kbd>Enter</kbd> or <kbd>Space</kbd> opens one.
* **A focus ring that isn't clipped.** The ring is drawn on the item around the button, outside the overlay caption's clip, with the kit's offset gap.
* **Captions.** Overlay captions keep Figure's 4.5:1 scrim, and its solid `Canvas` surface in forced colors. They're read after the photo, inside a `<figure>`. Under a provider, clicks on a caption go through to the tile's button.
* **Alt and caption.** They do different jobs: don't repeat one in the other. See [Figure](/docs/figure#alt-text-and-captions).
* **Right-to-left.** Logical properties only; see [Right-to-left](#right-to-left).

## Internationalization [#internationalization]

`Gallery`'s one string of its own is the label of a decorative photo's open button. Alt text and captions are your content: translate them with the rest of the page.

| Key         | Default                                                        | Receives                                                                                                                        |
| ----------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `openLabel` | ``(position, count) => `Open image ${position} of ${count}` `` | The 1-based position and the count, already formatted with `Intl.NumberFormat` for the locale from [`IntlProvider`](/docs/intl) |

```tsx
<Gallery
  data={photos.map((photo) => ({ ...photo, alt: t('photos.alt', photo) }))}
  translations={{ openLabel: (position, count) => t('photos.open', { position, count }) }}
/>
```
