API
SlidePositions
The previous, current and next index onChange reports whenever the selected slide changes.
What it is
onChange reports where the carousel is together with its neighbours, counted from zero. It is the callback for work that depends on what comes next — preloading the following image, pausing a video on the slide being left, reporting the slide that was reached.
type SlidePositions = {
prev: number
current: number
next: number
}| Field | Type | Description |
|---|---|---|
prev | number | The snap before the current one. Clamped to 0 at the start, or wrapped to the last snap when loop is on. |
current | number | The selected snap — the same value as selectedIndex. |
next | number | The snap after the current one. Clamped to the last snap at the end, or wrapped to 0 when loop is on. |
Usage
const [carouselRef] = useSwipiCarousel({
loop: true,
onChange: ({ prev, current, next }) => {
preload(items[next])
preload(items[prev])
track('slide_viewed', { index: current })
}
})onChange or onSelect
onChange fires when the index moves and tells you where you came from and where you can go. onSelect fires on every state change, including a snap count that shifted because the viewport was resized, and hands back the whole navigable state. Use the first for reacting to a move, the second for mirroring the state somewhere else.
Both are read through a ref and both make their first call once the carousel has been measured.
