|Kit

useOpenIndex

The open-index seam behind Gallery, Carousel and Lightbox. useOpenIndexTrigger turns an element of your own into an item that opens a viewer, with focus coming back to it.

A collection of media (a Gallery's tiles, a Carousel's slides) never imports what shows an item larger. It reads the open-index seam instead: an OpenIndexProvider above it, usually a Lightbox, says "open item N". With no provider, the items stay plain images and nothing is focusable.

Two hooks expose the seam:

  • useOpenIndexTrigger(index) turns an element of your own into an item: a list row, a table cell, a map pin. Reach for it when your own layout should open in a Lightbox.
  • useOpenIndex() reads the provider itself, for anything the trigger doesn't cover.
import { useOpenIndexTrigger } from '@42-central/ui-react';

function PhotoRow({ photo, index }) {
  const trigger = useOpenIndexTrigger(index);
  if (!trigger) return <div>{photo.alt}</div>;
  return <button {...trigger}>{photo.alt}</button>;
}

Usage

A list of your own inside a Lightbox. Each row opens the lightbox at its own index; navigate to another photo and close, and focus lands on that photo's row, not the one you opened from.

Code

function PhotoRow({ photo, index }) {
  const trigger = useOpenIndexTrigger(index);
  if (!trigger) return <div>{photo.alt}</div>;
  return (
    <button {...trigger}>
      <Image src={photo.src} alt="" ratio={1} />
      {photo.alt}
    </button>
  );
}

<Lightbox data={photos}>
  <ul>
    {photos.map((photo, index) => (
      <li key={photo.key}><PhotoRow photo={photo} index={index} /></li>
    ))}
  </ul>
</Lightbox>

To provide the seam yourself, to open a route or a side panel instead of a lightbox, see Gallery › Opening a photo.

API

useOpenIndexTrigger(index, reveal?)

Prop

Type

Returns undefined with no provider, so you render no button at all. Under a provider, spread the props it returns onto a <button>:

Prop

Type

The button needs an accessible name: visible text, or the image's alt.

useOpenIndex()

Returns the nearest provider's OpenIndex, or undefined when items should stay inert.

Prop

Type

OpenIndexProvider takes that object as value. Keep it referentially stable (useMemo): every item registers again when it changes.

On this page