UIPackage React Native
Search

Video

Foreground-only Expo video with system controls, request lifecycle, error recovery and fullscreen. Bare RN requires Expo Modules.

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 video

Source files

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

components/ui/video/Video.tsx
import * as React from 'react'
import { AppState, Platform, StyleSheet, View, type ViewProps } from 'react-native'
import {
  VideoView,
  useVideoPlayer,
  type VideoSource,
  type VideoPlayerStatus,
  type PlayerError,
  type VideoViewProps,
} from 'expo-video'
import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/spinner'
import { Text } from '@/components/ui/text'
import { cn } from '@/lib/utils'

export interface VideoHandle {
  play: () => void
  pause: () => void
  replay: () => void
  enterFullscreen: () => Promise<void>
}

/** Expo Modules must be configured in bare RN. Backgrounding pauses playback; returning never resumes it. */
export interface VideoProps extends Omit<ViewProps, 'children'> {
  source: VideoSource
  /** Set false when a retained route loses focus. Returning does not resume playback. */
  active?: boolean
  muted?: boolean
  loop?: boolean
  aspectRatio?: number
  className?: string
  fullscreenOptions?: NonNullable<VideoViewProps['fullscreenOptions']>
  errorMessage?: string
  retryLabel?: string
  onStatusChange?: (status: VideoPlayerStatus, error?: PlayerError) => void
  onPlayingChange?: (playing: boolean) => void
}

function hasSource(source: VideoSource) {
  if (typeof source === 'string') return !!source.trim()
  if (typeof source === 'number') return Number.isFinite(source) && source > 0
  return !!source && (!!source.uri?.trim() || (typeof source.assetId === 'number' && source.assetId > 0))
}

const VideoSession = React.forwardRef<VideoHandle, VideoProps & { retry: () => void }>(
  (
    {
      source,
      active = true,
      muted = false,
      loop = false,
      aspectRatio = 16 / 9,
      className,
      style,
      fullscreenOptions = { enable: true },
      errorMessage = 'The video could not be loaded.',
      retryLabel = 'Retry video',
      onStatusChange,
      onPlayingChange,
      retry,
      accessibilityLabel = 'Video',
      ...props
    },
    ref,
  ) => {
    const supplied = hasSource(source)
    const player = useVideoPlayer(supplied ? source : null)
    const view = React.useRef<VideoView>(null)
    const alive = React.useRef(true)
    const [status, setStatus] = React.useState(player.status)
    const [foreground, setForeground] = React.useState(AppState.currentState === 'active')
    const visible = Platform.OS !== 'web' || foreground
    const available = React.useRef(active && visible)
    available.current = active && visible
    const callbacks = React.useRef({ onStatusChange, onPlayingChange })
    callbacks.current = { onStatusChange, onPlayingChange }

    React.useLayoutEffect(() => {
      alive.current = true
      return () => {
        alive.current = false
      }
    }, [])
    React.useEffect(() => {
      player.loop = loop
      player.muted = muted
      player.staysActiveInBackground = false
      player.showNowPlayingNotification = false
    }, [player, loop, muted])
    React.useEffect(() => {
      if (!active) player.pause()
    }, [player, active])
    React.useEffect(() => {
      // Native Expo owns app/fullscreen activity transitions. Android fullscreen
      // pauses the React host while its separate player activity stays visible.
      if (Platform.OS !== 'web') return
      const subscription = AppState.addEventListener('change', (state) => {
        const next = state === 'active'
        available.current = active && next
        setForeground(next)
        if (!next) player.pause()
      })
      return () => subscription.remove()
    }, [player, active])
    React.useEffect(() => {
      const statusSubscription = player.addListener('statusChange', (event) => {
        if (!alive.current) return
        setStatus(event.status)
        callbacks.current.onStatusChange?.(event.status, event.error)
      })
      const playingSubscription = player.addListener('playingChange', ({ isPlaying }) => {
        if (!alive.current) return
        if (isPlaying && !available.current) {
          player.pause()
          return
        }
        callbacks.current.onPlayingChange?.(isPlaying)
      })
      setStatus(player.status)
      callbacks.current.onStatusChange?.(player.status)
      callbacks.current.onPlayingChange?.(player.playing)
      return () => {
        statusSubscription.remove()
        playingSubscription.remove()
      }
    }, [player])
    React.useImperativeHandle(
      ref,
      () => ({
        play: () => {
          if (alive.current && available.current && supplied && player.status !== 'error') player.play()
        },
        pause: () => {
          if (alive.current) player.pause()
        },
        replay: () => {
          if (!alive.current || !available.current || !supplied || player.status === 'error') return
          player.currentTime = 0
          player.play()
        },
        enterFullscreen: async () => {
          if (alive.current && available.current && fullscreenOptions.enable) await view.current?.enterFullscreen()
        },
      }),
      [player, supplied, fullscreenOptions.enable],
    )

    const failed = !supplied || status === 'error'
    return (
      <View {...props} className={cn('w-full gap-[12px]', className)} style={style}>
        {failed ? (
          <View className="min-h-[144px] items-center justify-center gap-[12px] rounded-lg border border-border bg-muted p-[16px]">
            <Text>{supplied ? errorMessage : 'No video supplied.'}</Text>
            {supplied ? (
              <Button variant="outline" onPress={retry}>
                {retryLabel}
              </Button>
            ) : null}
          </View>
        ) : (
          <View
            className="overflow-hidden rounded-lg bg-black"
            style={{ aspectRatio: Number.isFinite(aspectRatio) && aspectRatio > 0 ? aspectRatio : 16 / 9 }}
          >
            {/* SDK54's web imperative entry still reads the legacy fullscreen flag. */}
            <VideoView
              ref={view}
              player={player}
              accessibilityLabel={accessibilityLabel}
              style={StyleSheet.absoluteFill}
              pointerEvents={active && visible ? 'auto' : 'none'}
              nativeControls={active && visible}
              contentFit="contain"
              fullscreenOptions={fullscreenOptions}
              {...(Platform.OS === 'web' && { allowsFullscreen: fullscreenOptions.enable })}
              allowsPictureInPicture={false}
              startsPictureInPictureAutomatically={false}
              playsInline
            />
            {status === 'loading' ? (
              <View pointerEvents="none" className="absolute inset-0 items-center justify-center">
                <Spinner accessibilityLabel="Loading video" color="white" />
              </View>
            ) : null}
          </View>
        )}
      </View>
    )
  },
)
VideoSession.displayName = 'VideoSession'

export const Video = React.forwardRef<VideoHandle, VideoProps>((props, ref) => {
  const [attempt, setAttempt] = React.useState(0)
  return (
    <VideoSession
      {...props}
      ref={ref}
      key={JSON.stringify(props.source) + ':' + attempt}
      retry={() => setAttempt((value) => value + 1)}
    />
  )
})
Video.displayName = 'Video'
components/ui/video/index.ts
export { Video, type VideoHandle, type VideoProps } from './Video'

Dependencies

Registry items

npm packages

  • expo-video
Browse content and media