UIPackage React Native
Search

Carousel

Native paged scrolling with measured slide widths and composed page controls.

Install

First install? Set up the registry in your app.

npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add carousel

Source files

Expand a file to read the source the installer copies into your app.

components/ui/carousel/Carousel.tsx
import * as React from 'react'
import { I18nManager, Pressable, ScrollView, View, type ScrollViewProps, type ViewProps } from 'react-native'
import { useReducedMotion } from 'react-native-reanimated'
import { Button, type ButtonProps } from '@/components/ui/button'
import { Text, type TextProps } from '@/components/ui/text'
import { renderTextChildren } from '@/lib/label-children'
import { cn } from '@/lib/utils'

interface CarouselState {
  index: number
  count: number
  width: number
  disabled: boolean
  scroll: React.RefObject<React.ComponentRef<typeof ScrollView> | null>
  setWidth: (width: number) => void
  setCount: (count: number) => void
  settle: (index: number) => void
  go: (index: number) => void
}
const Context = React.createContext<CarouselState | null>(null)
function useCarousel() {
  const value = React.useContext(Context)
  if (!value) throw new Error('Carousel parts must be inside Carousel')
  return value
}
function clamp(index: number, count: number) {
  return Math.max(0, Math.min(Math.max(0, count - 1), Number.isFinite(index) ? Math.trunc(index) : 0))
}
export interface CarouselProps extends ViewProps {
  index?: number
  defaultIndex?: number
  onIndexChange?: (index: number) => void
  disabled?: boolean
  className?: string
}
export const Carousel = React.forwardRef<React.ComponentRef<typeof View>, CarouselProps>(
  ({ index, defaultIndex = 0, onIndexChange, disabled = false, className, ...props }, ref) => {
    const [internal, setInternal] = React.useState(defaultIndex)
    const [count, setCount] = React.useState(0)
    const [width, setWidth] = React.useState(0)
    const [settled, setSettled] = React.useState({ index: 0 })
    const scroll = React.useRef<React.ComponentRef<typeof ScrollView>>(null)
    const previousWidth = React.useRef(0)
    const reduced = useReducedMotion()
    const current = clamp(index ?? internal, count)
    const controlled = index !== undefined
    const registerCount = React.useCallback(
      (next: number) => {
        setCount(next)
        if (!controlled) setInternal((value) => clamp(value, next))
      },
      [controlled],
    )
    function go(next: number) {
      if (disabled || !count) return
      const target = clamp(next, count)
      if (target === current) return
      if (!controlled) setInternal(target)
      onIndexChange?.(target)
    }
    React.useLayoutEffect(() => {
      if (!width) return
      scroll.current?.scrollTo({
        x: current * width,
        y: 0,
        animated: !reduced && previousWidth.current === width && current !== settled.index,
      })
      previousWidth.current = width
      // `count` is deliberately absent: appending slides keeps the page, and iOS scrollTo would stop a live drag.
    }, [current, width, settled, reduced])
    return (
      <Context.Provider
        value={{
          index: current,
          count,
          width,
          scroll,
          disabled,
          setWidth,
          setCount: registerCount,
          go,
          settle: (next) => {
            setSettled({ index: next })
            go(next)
          },
        }}
      >
        <View {...props} ref={ref} className={cn('w-full gap-[12px]', className)} />
      </Context.Provider>
    )
  },
)
Carousel.displayName = 'Carousel'

function pages(children: React.ReactNode, namespace = ''): React.ReactNode[] {
  return React.Children.toArray(children).flatMap((child) => {
    if (!React.isValidElement<{ children?: React.ReactNode }>(child)) return [child]
    const key = namespace + '/' + child.key
    if (child.type === React.Fragment) return pages(child.props.children, key)
    return [React.cloneElement(child, { key })]
  })
}
export type CarouselContentProps = Omit<
  ScrollViewProps,
  'horizontal' | 'pagingEnabled' | 'children' | 'contentContainerStyle'
> & {
  children?: React.ReactNode
  className?: string
}
export const CarouselContent = React.forwardRef<React.ComponentRef<typeof ScrollView>, CarouselContentProps>(
  ({ children, className, onLayout, onMomentumScrollEnd, onScrollEndDrag, scrollEnabled, ...props }, ref) => {
    const carousel = useCarousel()
    const content = pages(children)
    const { setCount } = carousel
    React.useLayoutEffect(() => {
      setCount(content.length)
    }, [setCount, content.length])
    React.useImperativeHandle(ref, () => carousel.scroll.current!, [carousel.scroll])
    return (
      <ScrollView
        {...props}
        ref={carousel.scroll}
        horizontal
        pagingEnabled
        scrollEnabled={!carousel.disabled && scrollEnabled !== false && content.length > 1}
        showsHorizontalScrollIndicator={false}
        className={cn('w-full rounded-lg', className)}
        onLayout={(event) => {
          carousel.setWidth(Math.max(0, event.nativeEvent.layout.width))
          onLayout?.(event)
        }}
        onScrollEndDrag={(event) => {
          // iOS only: when UIKit's paging target equals the current offset it will not decelerate, and no
          // onMomentumScrollEnd follows. Android sends no target and always ends with a momentum event.
          const { contentOffset, targetContentOffset, contentSize, layoutMeasurement } = event.nativeEvent
          if (carousel.width && targetContentOffset) {
            // iOS reports contentOffset in logical (RTL-adjusted) space but targetContentOffset physically.
            const target = I18nManager.isRTL
              ? contentSize.width - layoutMeasurement.width - targetContentOffset.x
              : targetContentOffset.x
            if (Math.abs(target - contentOffset.x) < 0.5)
              carousel.settle(clamp(Math.round(contentOffset.x / carousel.width), content.length))
          }
          onScrollEndDrag?.(event)
        }}
        onMomentumScrollEnd={(event) => {
          if (carousel.width)
            carousel.settle(clamp(Math.round(event.nativeEvent.contentOffset.x / carousel.width), content.length))
          onMomentumScrollEnd?.(event)
        }}
      >
        {content}
      </ScrollView>
    )
  },
)
CarouselContent.displayName = 'CarouselContent'
export const CarouselItem = React.forwardRef<React.ComponentRef<typeof View>, ViewProps & { className?: string }>(
  ({ children, className, style, ...props }, ref) => {
    const carousel = useCarousel()
    return (
      <View {...props} ref={ref} className={cn('shrink-0', className)} style={[{ width: carousel.width }, style]}>
        {renderTextChildren(children)}
      </View>
    )
  },
)
CarouselItem.displayName = 'CarouselItem'
export const CarouselPrevious = React.forwardRef<React.ComponentRef<typeof Pressable>, ButtonProps>(
  ({ children = 'Previous slide', disabled, onPress, ...props }, ref) => {
    const carousel = useCarousel()
    const isDisabled = carousel.disabled || !!disabled || carousel.index <= 0 || !carousel.count
    return (
      <Button
        variant="outline"
        {...props}
        ref={ref}
        disabled={isDisabled}
        onPress={(event) => {
          if (isDisabled) return
          onPress?.(event)
          if (!event.isDefaultPrevented()) carousel.go(carousel.index - 1)
        }}
      >
        {children}
      </Button>
    )
  },
)
CarouselPrevious.displayName = 'CarouselPrevious'
export const CarouselNext = React.forwardRef<React.ComponentRef<typeof Pressable>, ButtonProps>(
  ({ children = 'Next slide', disabled, onPress, ...props }, ref) => {
    const carousel = useCarousel()
    const isDisabled = carousel.disabled || !!disabled || !carousel.count || carousel.index >= carousel.count - 1
    return (
      <Button
        variant="outline"
        {...props}
        ref={ref}
        disabled={isDisabled}
        onPress={(event) => {
          if (isDisabled) return
          onPress?.(event)
          if (!event.isDefaultPrevented()) carousel.go(carousel.index + 1)
        }}
      >
        {children}
      </Button>
    )
  },
)
CarouselNext.displayName = 'CarouselNext'
export const CarouselStatus = React.forwardRef<React.ComponentRef<typeof Text>, TextProps>(
  ({ children, ...props }, ref) => {
    const carousel = useCarousel()
    return (
      <Text {...props} ref={ref}>
        {children ?? (carousel.count ? 'Slide ' + (carousel.index + 1) + ' of ' + carousel.count : 'No slides')}
      </Text>
    )
  },
)
CarouselStatus.displayName = 'CarouselStatus'
components/ui/carousel/index.ts
export * from './Carousel'

Dependencies

Registry items

npm packages

  • react-native-reanimated
Browse more components