High-Performance React Native OTP Input Component

Description:

react-native-input-code-otp is a high-performance One-Time Password input component inspired by shadcn/ui design system.

It breaks down the OTP input into composable parts: a root TextInputOTP container, TextInputOTPGroup for logical grouping of digits, TextInputOTPSlot for each individual input field, and an optional TextInputOTPSeparator for visual division. This architecture gives you precise control over the layout and styling of each element.

Features

  • 🎨 Full customization control – Modify styles for individual slots, focused states, and separators to match your app’s design system.
  • ♿ Built-in accessibility – Includes proper labels and hints for screen readers to ensure an inclusive user experience.
  • 🚀 Optimized performance – Implements efficient rendering that maintains smooth interactions even during rapid input.
  • 🔒 Complete type safety – Offers full TypeScript support with comprehensive type definitions for all components and props.
  • 🎯 Programmatic control – Access component methods through refs to clear, focus, blur, or set values dynamically.
  • 📱 Flexible layouts – Configure various OTP code lengths and group slots with custom separators for different authentication requirements.
  • 🔄 Form integration – Compatible with popular form libraries like react-hook-form through controlled component implementation.

Preview

high-performance-otp-input

Use Cases

  • Two-Factor Authentication (2FA): Add an extra layer of security to your login process by requiring users to enter a code sent to their device.
  • Phone Number Verification: Confirm user identity during account registration or profile updates by sending an OTP via SMS.
  • Password Resets: Securely verify a user’s identity before allowing them to reset their password.
  • Transaction Confirmation: Authorize payments or other critical actions within your application by requiring an OTP.

How to Use It

1. Install the component with NPM

npm install react-native-input-code-otp

2. Import the necessary components from the library. The main wrapper is TextInputOTP, and each digit is represented by a TextInputOTPSlot.

You must provide the maxLength prop to the TextInputOTP component to define the number of expected digits. The onFilled callback is a convenient function that executes once the user has entered the complete code.

Here is an example of a simple 4-digit OTP input:

import { TextInputOTP, TextInputOTPSlot, TextInputOTPGroup } from 'react-native-input-code-otp';
export function OtpExample() {
  return (
    <TextInputOTP maxLength={4} onFilled={(code) => console.log(code)}>
      <TextInputOTPGroup>
        <TextInputOTPSlot index={0} />
        <TextInputOTPSlot index={1} />
        <TextInputOTPSlot index={2} />
        <TextInputOTPSlot index={3} />
      </TextInputOTPGroup>
    </TextInputOTP>
  );
}

3. You can customize the appearance of the input fields using various style props. For instance, you can change the border color of a slot when it is focused or adjust the text style. The TextInputOTPSeparator component allows you to add visual dividers between groups of inputs.

This example shows a 6-digit input with a separator and custom styles for focused slots.

import {
  TextInputOTP,
  TextInputOTPSlot,
  TextInputOTPGroup,
  TextInputOTPSeparator,
} from 'react-native-input-code-otp';
export function StyledOtpExample() {
  return (
    <TextInputOTP
      maxLength={6}
      caretColor="#007AFF"
      onFilled={(code) => {
        alert(`OTP Entered: ${code}`);
      }}
    >
      <TextInputOTPGroup>
        <TextInputOTPSlot index={0} focusedSlotStyles={{ borderColor: '#007AFF' }} />
        <TextInputOTPSlot index={1} focusedSlotStyles={{ borderColor: '#007AFF' }} />
        <TextInputOTPSlot index={2} focusedSlotStyles={{ borderColor: '#007AFF' }} />
      </TextInputOTPGroup>
      <TextInputOTPSeparator />
      <TextInputOTPGroup>
        <TextInputOTPSlot index={3} focusedSlotStyles={{ borderColor: '#007AFF' }} />
        <TextInputOTPSlot index={4} focusedSlotStyles={{ borderColor: '#007AFF' }} />
        <TextInputOTPSlot index={5} focusedSlotStyles={{ borderColor: '#007AFF' }} />
      </TextInputOTPGroup>
    </TextInputOTP>
  );
}

4. For more advanced control, you can use a ref to access the component’s methods. This is useful for clearing the input after a failed submission or programmatically filling the value, for instance, from a clipboard action.

The ref exposes four methods: clear() to reset all inputs, focus() to bring the first slot into focus, blur() to remove focus, and setValue('123456') to programmatically fill the inputs.

import { useRef } from 'react';
import { Button, View } from 'react-native';
import { TextInputOTP, TextInputOTPSlot, TextInputOTPGroup, type TextInputOTPRef } from 'react-native-input-code-otp';
export function RefExample() {
  const inputRef = useRef<TextInputOTPRef>(null);
  const handleClear = () => {
    inputRef.current?.clear();
  };
  const handleFill = () => {
    inputRef.current?.setValue('987654');
  };
  return (
    <View>
      <TextInputOTP ref={inputRef} maxLength={6}>
        <TextInputOTPGroup>
          <TextInputOTPSlot index={0} />
          <TextInputOTPSlot index={1} />
          <TextInputOTPSlot index={2} />
          <TextInputOTPSlot index={3} />
          <TextInputOTPSlot index={4} />
          <TextInputOTPSlot index={5} />
        </TextInputOTPGroup>
      </TextInputOTP>
      <Button title="Clear Input" onPress={handleClear} />
      <Button title="Fill Input" onPress={handleFill} />
    </View>
  );
}

Related Resources

  • react-native-confirmation-code-field: A highly customizable confirmation code field that provides a low-level API for creating unique UIs.
  • react-native-otp-textinput: A component for entering OTPs and PINs with extensive styling options for individual input cells.
  • React Hook Form: A performant and flexible library for managing forms in React and React Native, which integrates well with this OTP component.
  • Formik: A popular library for building forms in React and React Native that helps with form state, validation, and submission.

FAQs

Q: How can I customize the appearance of each OTP input box?
A: You can use the slotStyles and focusedSlotStyles props on the TextInputOTPSlot component to apply custom ViewStyle objects. Similarly, use slotTextStyles and focusedSlotTextStyles for TextStyle customizations.

Q: How do I get the completed code?
A: You can use the onFilled prop on the TextInputOTP component. It is a callback function that receives the complete OTP string as its only argument when all slots have been filled.

Q: What is the maximum code length supported?
A: The component supports configurable code lengths through the maxLength prop. While typical OTP codes use 4-6 digits, you can implement longer verification sequences by adjusting this prop and configuring corresponding slots.

Q: How do I handle the input when the user has not filled all the slots?
A: The component only triggers onFilled when the input is complete. For partial input handling, you would need to manage the state yourself via a ref or a form library.

Q: Can I have more than one separator in my layout?
A: Yes, you can place multiple TextInputOTPSeparator components anywhere between your groups.

Add Comment