UIPackage React Native
Search

Combobox

Searchable single or multiple selection with composed options and native sheet dismissal.

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 combobox

Source files

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

components/ui/combobox/Combobox.tsx
import * as React from 'react'
import { Platform, Pressable, View, type PressableProps, type ViewProps } from 'react-native'
import { Check, ChevronDown } from 'lucide-react-native'
import { Button, type ButtonProps } from '@/components/ui/button'
import { SearchBar, type SearchBarProps } from '@/components/ui/search-bar'
import { Sheet, SheetContent, type SheetContentProps } from '@/components/ui/sheet'
import { Text } from '@/components/ui/text'
import { useOverlay, useOverlayTriggerRef, type OverlayProps } from '@/lib/overlay'
import { useThemeColors } from '@/lib/theme'
import { cn } from '@/lib/utils'
import { renderTextChildren } from '@/lib/label-children'

export interface ComboboxOption {
  value: string
  label: string
}
interface CommonProps extends OverlayProps {
  disabled?: boolean
}
export type ComboboxProps = CommonProps &
  (
    | {
        multiple?: false
        value?: ComboboxOption | null
        defaultValue?: ComboboxOption | null
        onValueChange?: (value: ComboboxOption | null) => void
      }
    | {
        multiple: true
        value?: ComboboxOption[]
        defaultValue?: ComboboxOption[]
        onValueChange?: (value: ComboboxOption[]) => void
      }
  )
interface ChoiceContext {
  selected: ComboboxOption[]
  multiple: boolean
  disabled: boolean
  query: string
  setQuery: (query: string) => void
  choose: (option: ComboboxOption) => void
  clear: () => void
  matches: (text: string) => boolean
  register: (id: string, text: string) => () => void
  hasMatches: boolean
}
const Context = React.createContext<ChoiceContext | null>(null)
function useChoice() {
  const context = React.useContext(Context)
  if (!context) throw new Error('Combobox parts must be inside Combobox')
  return context
}
function array(value: ComboboxOption | ComboboxOption[] | null | undefined) {
  return Array.isArray(value) ? value : value ? [value] : []
}
function matches(text: string, query: string) {
  return text.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())
}

export function Combobox(props: ComboboxProps) {
  const {
    children,
    disabled = false,
    value,
    defaultValue,
    onValueChange: _onValueChange,
    multiple = false,
    ...overlay
  } = props
  const [internal, setInternal] = React.useState(() => array(defaultValue))
  const [query, setQuery] = React.useState('')
  const [entries, setEntries] = React.useState<Map<string, string>>(() => new Map())
  const selected = value === undefined ? internal : array(value)
  const register = React.useCallback((id: string, text: string) => {
    setEntries((previous) => new Map(previous).set(id, text))
    return () =>
      setEntries((previous) => {
        if (!previous.has(id)) return previous
        const next = new Map(previous)
        next.delete(id)
        return next
      })
  }, [])
  function publish(next: ComboboxOption[]) {
    if (disabled) return
    if (value === undefined) setInternal(next)
    if (props.multiple) props.onValueChange?.(next)
    else props.onValueChange?.(next[0] ?? null)
  }
  return (
    <Context.Provider
      value={{
        selected,
        multiple,
        disabled,
        query,
        setQuery,
        register,
        hasMatches: [...entries.values()].some((text) => matches(text, query)),
        matches: (text) => matches(text, query),
        choose: (option) => {
          if (disabled) return
          const checked = selected.some((item) => item.value === option.value)
          if (multiple)
            publish(checked ? selected.filter((item) => item.value !== option.value) : [...selected, option])
          else if (!checked) publish([option])
        },
        clear: () => {
          if (selected.length) publish([])
        },
      }}
    >
      <Sheet {...overlay}>{children}</Sheet>
    </Context.Provider>
  )
}

export interface ComboboxTriggerProps extends Omit<ButtonProps, 'variant' | 'textClassName' | 'size'> {
  size?: Exclude<ButtonProps['size'], 'icon'>
  placeholder?: string
  invalid?: boolean
}
export const ComboboxTrigger = React.forwardRef<React.ComponentRef<typeof Pressable>, ComboboxTriggerProps>(
  (
    {
      placeholder = 'Choose an option',
      invalid,
      disabled,
      onPress,
      children,
      className,
      accessibilityState,
      accessibilityValue,
      ...props
    },
    ref,
  ) => {
    const choice = useChoice()
    const overlay = useOverlay()
    const trigger = useOverlayTriggerRef(ref)
    const colors = useThemeColors()
    const isDisabled = choice.disabled || !!disabled
    const label = choice.selected.map((item) => item.label).join(', ')
    return (
      <Button
        {...props}
        ref={trigger.ref}
        variant="outline"
        accessibilityRole={Platform.OS === 'ios' ? 'button' : 'combobox'}
        accessibilityState={{ ...accessibilityState, disabled: isDisabled, expanded: overlay.open }}
        accessibilityValue={{ ...accessibilityValue, text: label || placeholder }}
        disabled={isDisabled}
        className={cn('justify-between', invalid && 'border-destructive', className)}
        onPress={(event) => {
          if (isDisabled) return
          onPress?.(event)
          if (event.isDefaultPrevented()) return
          trigger.capture()
          overlay.setOpen(true)
        }}
      >
        <Text className={cn('min-w-0 flex-1', !label && 'text-muted-foreground')}>
          {children ?? (label || placeholder)}
        </Text>
        <ChevronDown size={20} color={colors.foreground} aria-hidden />
      </Button>
    )
  },
)
ComboboxTrigger.displayName = 'ComboboxTrigger'

export const ComboboxContent = React.forwardRef<React.ComponentRef<typeof View>, SheetContentProps>((props, ref) => (
  <SheetContent ref={ref} {...props} />
))
ComboboxContent.displayName = 'ComboboxContent'
export type ComboboxContentProps = SheetContentProps

export type ComboboxSearchProps = Omit<SearchBarProps, 'value' | 'defaultValue' | 'onChangeText'>
export const ComboboxSearch = React.forwardRef<React.ComponentRef<typeof SearchBar>, ComboboxSearchProps>(
  ({ editable, accessibilityLabel = 'Search options', ...props }, ref) => {
    const choice = useChoice()
    return (
      <SearchBar
        ref={ref}
        {...props}
        accessibilityLabel={accessibilityLabel}
        value={choice.query}
        onChangeText={choice.setQuery}
        editable={!choice.disabled && editable !== false}
      />
    )
  },
)
ComboboxSearch.displayName = 'ComboboxSearch'

export interface ComboboxItemProps extends Omit<PressableProps, 'children'> {
  children?: React.ReactNode
  value: string
  label: string
  searchText?: string
  className?: string
}
export const ComboboxItem = React.forwardRef<React.ComponentRef<typeof Pressable>, ComboboxItemProps>(
  ({ value, label, searchText = label, children, disabled, onPress, className, accessibilityState, ...props }, ref) => {
    const choice = useChoice()
    const { setOpen } = useOverlay()
    const colors = useThemeColors()
    const id = React.useId()
    const { register } = choice
    React.useLayoutEffect(() => register(id, searchText), [register, id, searchText])
    if (!choice.matches(searchText)) return null
    const checked = choice.selected.some((option) => option.value === value)
    const isDisabled = choice.disabled || !!disabled
    return (
      <Pressable
        {...props}
        ref={ref}
        disabled={isDisabled}
        accessibilityRole={choice.multiple ? 'checkbox' : 'radio'}
        accessibilityLabel={props.accessibilityLabel ?? label}
        accessibilityState={{ ...accessibilityState, disabled: isDisabled, checked }}
        className={cn(
          'min-h-[48px] flex-row items-center gap-[12px] rounded-md px-[12px] py-[12px] active:bg-muted',
          checked && 'bg-secondary',
          isDisabled && 'opacity-50',
          className,
        )}
        onPress={(event) => {
          if (isDisabled) return
          onPress?.(event)
          if (event.isDefaultPrevented()) return
          choice.choose({ value, label })
          if (!choice.multiple) setOpen(false)
        }}
      >
        <View pointerEvents="none" aria-hidden className="min-w-0 flex-1 gap-[4px]">
          <Text className="font-medium">{label}</Text>
          {renderTextChildren(children, 'text-muted-foreground')}
        </View>
        <View pointerEvents="none" aria-hidden className="size-[20px] items-center justify-center">
          {checked ? <Check size={20} color={colors.foreground} aria-hidden /> : null}
        </View>
      </Pressable>
    )
  },
)
ComboboxItem.displayName = 'ComboboxItem'

export const ComboboxEmpty = React.forwardRef<React.ComponentRef<typeof View>, ViewProps & { className?: string }>(
  ({ children = <Text variant="muted">No matching options.</Text>, className, ...props }, ref) => {
    const choice = useChoice()
    if (choice.hasMatches) return null
    return (
      <View {...props} ref={ref} className={cn('p-[16px]', className)}>
        {children}
      </View>
    )
  },
)
ComboboxEmpty.displayName = 'ComboboxEmpty'

export const ComboboxClear = React.forwardRef<React.ComponentRef<typeof Pressable>, ButtonProps>(
  ({ children = 'Clear selection', disabled, onPress, ...props }, ref) => {
    const choice = useChoice()
    const isDisabled = choice.disabled || !!disabled || !choice.selected.length
    return (
      <Button
        {...props}
        ref={ref}
        disabled={isDisabled}
        onPress={(event) => {
          if (isDisabled) return
          onPress?.(event)
          if (!event.isDefaultPrevented()) choice.clear()
        }}
      >
        {children}
      </Button>
    )
  },
)
ComboboxClear.displayName = 'ComboboxClear'
export { SheetClose as ComboboxClose } from '@/components/ui/sheet'
components/ui/combobox/index.ts
export * from './Combobox'

Dependencies

Registry items

npm packages

  • lucide-react-native
  • react-native-svg
Browse more components