API
SwipiState
The snapshot onSelect receives on every change, for everything that lives outside the component.
What it is
SwipiState is the navigable part of the carousel without the methods — the snapshot onSelect receives on every change.
tsx
type SwipiState = {
selectedIndex: number
snapCount: number
canScrollNext: boolean
canScrollPrev: boolean
}| Field | Type | Description |
|---|---|---|
selectedIndex | number | Index of the currently selected snap position. |
snapCount | number | Total number of snap positions. |
canScrollNext | boolean | Whether a next scroll is currently possible. |
canScrollPrev | boolean | Whether a previous scroll is currently possible. |
When to use it
Reading the carousel object is enough for the UI around the carousel. onSelect is for everything that lives further away — a progress bar in a sibling component, an analytics call, a store. It is the same callback in every framework.
React
import { useState } from 'react'
import { useSwipiCarousel, type SwipiState } from '@midstem/swipi-react'
export const App = () => {
const [state, setState] = useState<SwipiState>()
const [carouselRef] = useSwipiCarousel({ onSelect: setState })
return (
<>
<div ref={carouselRef}>
<div>
<div>one</div>
<div>two</div>
</div>
</div>
<p>
Slide {(state?.selectedIndex ?? 0) + 1} of {state?.snapCount}
</p>
</>
)
}When it fires
The first call lands right after the carousel is measured, so a state initialised as undefined is filled in before the browser paints. After that it fires whenever the selected index, the snap count or either scroll flag changes.
React
const [progress, setProgress] = useState(0)
const [carouselRef] = useSwipiCarousel({
onSelect: ({ selectedIndex, snapCount }) =>
setProgress((selectedIndex + 1) / snapCount)
})