UIPackage React Native
Search

Otp Input

Single native text input for paste/autofill codes with composed display slots and complete-value callbacks.

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 otp-input

Source files

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

components/ui/otp-input/OtpInput.tsx
import * as React from 'react'
import { Platform, TextInput, View, type TextInputProps, type ViewProps } from 'react-native'
import { Text } from '@/components/ui/text'
import { cn } from '@/lib/utils'

const OtpContext = React.createContext<{
  characters: string[]
  length: number
  focused: boolean
  activeIndex: number
  invalid: boolean
} | null>(null)

export interface OtpInputProps extends Omit<
  TextInputProps,
  | 'value'
  | 'defaultValue'
  | 'onChangeText'
  | 'maxLength'
  | 'multiline'
  | 'children'
  | 'style'
  | 'caretHidden'
  | 'secureTextEntry'
  | 'placeholder'
  | 'placeholderTextColor'
> {
  value?: string
  defaultValue?: string
  onValueChange?: (value: string) => void
  /** Runs once when the accepted value becomes complete, including an initially complete value. */
  onComplete?: (value: string) => void
  length?: number
  disabled?: boolean
  invalid?: boolean
  /** Numeric input strips separators from pasted codes. Text input preserves non-whitespace characters. */
  inputMode?: 'numeric' | 'text'
  className?: string
  style?: ViewProps['style']
  children?: React.ReactNode
}

export const OtpInput = React.forwardRef<React.ComponentRef<typeof TextInput>, OtpInputProps>(
  (
    {
      value,
      defaultValue = '',
      onValueChange,
      onComplete,
      length = 6,
      disabled = false,
      invalid = false,
      inputMode = 'numeric',
      editable = true,
      readOnly,
      className,
      style,
      children,
      onFocus,
      onBlur,
      onSelectionChange,
      autoComplete,
      autoCapitalize = 'none',
      autoCorrect = false,
      spellCheck = false,
      accessibilityLabel = 'One-time code',
      accessibilityState,
      ...props
    },
    ref,
  ) => {
    if (!Number.isInteger(length) || length < 1) throw new RangeError('OtpInput length must be a positive integer')
    const normalize = (text: string) =>
      Array.from(inputMode === 'numeric' ? text.replace(/\D/g, '') : text.replace(/\s/g, ''))
        .slice(0, length)
        .join('')
    const [internal, setInternal] = React.useState(() => normalize(defaultValue))
    const [focused, setFocused] = React.useState(false)
    const [selection, setSelection] = React.useState(0)
    const completed = React.useRef<string | undefined>(undefined)
    const resolved = normalize(value ?? internal)
    const characters = Array.from(resolved)
    const canEdit = editable && !disabled && !readOnly

    React.useEffect(() => {
      if (Array.from(resolved).length !== length) {
        completed.current = undefined
      } else if (completed.current !== resolved) {
        completed.current = resolved
        onComplete?.(resolved)
      }
    }, [resolved, length, onComplete])

    return (
      <OtpContext.Provider
        value={{
          characters,
          length,
          focused: focused && canEdit,
          activeIndex: Math.min(selection, length - 1),
          invalid,
        }}
      >
        <View
          className={cn('relative flex-row flex-wrap gap-[8px]', !canEdit && 'opacity-50', className)}
          style={style}
        >
          <View pointerEvents="none" aria-hidden className="max-w-full flex-row flex-wrap gap-[8px]">
            {children ?? Array.from({ length }, (_, index) => <OtpInputSlot key={index} index={index} />)}
          </View>
          <TextInput
            {...props}
            ref={ref}
            value={resolved}
            editable={canEdit}
            readOnly={readOnly}
            inputMode={inputMode}
            autoComplete={autoComplete ?? (Platform.OS === 'android' ? 'sms-otp' : 'one-time-code')}
            autoCorrect={autoCorrect}
            autoCapitalize={autoCapitalize}
            spellCheck={spellCheck}
            caretHidden
            underlineColorAndroid="transparent"
            multiline={false}
            accessibilityLabel={accessibilityLabel}
            accessibilityState={{ ...accessibilityState, disabled: !canEdit }}
            style={{
              position: 'absolute',
              left: 0,
              top: 0,
              right: 0,
              bottom: 0,
              color: 'transparent',
              backgroundColor: 'transparent',
              fontSize: 17,
            }}
            onChangeText={(text) => {
              if (!canEdit) return
              const next = normalize(text)
              if (value === undefined) setInternal(next)
              setSelection(Array.from(next).length)
              if (next !== resolved) onValueChange?.(next)
            }}
            onFocus={(event) => {
              setFocused(true)
              onFocus?.(event)
            }}
            onBlur={(event) => {
              setFocused(false)
              onBlur?.(event)
            }}
            onSelectionChange={(event) => {
              setSelection(Array.from(resolved.slice(0, event.nativeEvent.selection.start)).length)
              onSelectionChange?.(event)
            }}
          />
        </View>
      </OtpContext.Provider>
    )
  },
)
OtpInput.displayName = 'OtpInput'

export interface OtpInputSlotProps extends ViewProps {
  index: number
  className?: string
  placeholder?: string
}

export const OtpInputSlot = React.forwardRef<React.ComponentRef<typeof View>, OtpInputSlotProps>(
  ({ index, className, placeholder = '', ...props }, ref) => {
    const otp = React.useContext(OtpContext)
    if (!otp) throw new Error('OtpInputSlot must be inside OtpInput')
    if (!Number.isInteger(index) || index < 0 || index >= otp.length)
      throw new RangeError('OtpInputSlot index must be within the code length')
    const character = otp.characters[index]
    return (
      <View
        ref={ref}
        {...props}
        className={cn(
          'min-h-[56px] min-w-[48px] items-center justify-center rounded-md border border-input bg-background px-[8px] py-[12px]',
          otp.focused && otp.activeIndex === index && 'border-ring',
          otp.invalid && 'border-destructive',
          className,
        )}
      >
        <Text size="xl" className={cn('text-center font-medium', !character && 'text-muted-foreground')}>
          {character || placeholder}
        </Text>
      </View>
    )
  },
)
OtpInputSlot.displayName = 'OtpInputSlot'

export const OtpInputSeparator = React.forwardRef<React.ComponentRef<typeof View>, ViewProps & { className?: string }>(
  ({ className, ...props }, ref) => (
    <View ref={ref} {...props} className={cn('min-h-[56px] items-center justify-center', className)}>
      <Text variant="muted">–</Text>
    </View>
  ),
)
OtpInputSeparator.displayName = 'OtpInputSeparator'
components/ui/otp-input/index.ts
export { OtpInput, OtpInputSlot, OtpInputSeparator } from './OtpInput'
export type { OtpInputProps, OtpInputSlotProps } from './OtpInput'

Dependencies

Registry items

Browse controls and interactions