1.0.0 • Published 5 months ago

@thiengo105/react-otp-input v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

React OTP Input

A customizable OTP (One-Time Password) input component for React applications with TypeScript support.

Features

  • TypeScript support
  • Customizable length
  • Keyboard navigation
  • Paste support
  • Mobile-friendly numeric input
  • Accessible
  • Customizable styling
  • Disabled state support
  • Secure input mode
  • Form library integration (react-hook-form, Formik, etc.)

Installation

npm install react-otp-input
# or
yarn add react-otp-input

Usage

import { OtpInput } from 'react-otp-input';

function App() {
  const handleComplete = (value: string) => {
    console.log('OTP completed:', value);
  };

  return (
    <OtpInput
      length={6}
      onComplete={handleComplete}
      onChange={(value) => console.log('Current value:', value)}
      placeholder="○"
      disabled={false}
      style={{ margin: '20px' }}
      inputStyle={{ borderColor: '#000' }}
    />
  );
}

Props

PropTypeDefaultDescription
lengthnumber4Number of input fields
onChange(value: string) => void-Callback when value changes
onComplete(value: string) => void-Callback when all fields are filled
disabledbooleanfalseDisable the input fields
placeholderstring"○"Placeholder character
inputMode"numeric" | "tel""numeric"Input mode for mobile devices
styleReact.CSSProperties-Container style
inputStyleReact.CSSProperties-Individual input style
securebooleanfalseHide input values
maskCharstring"•"Character to use for masking
valuestring-Controlled input value
defaultValuestring""Default input value

Form Integration

React Hook Form

import { useForm, Controller } from 'react-hook-form';
import { OtpInput } from 'react-otp-input';

function Form() {
  const { control, handleSubmit } = useForm({
    defaultValues: {
      otp: ''
    }
  });

  const onSubmit = (data: { otp: string }) => {
    console.log('OTP:', data.otp);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        name="otp"
        control={control}
        rules={{ required: true, minLength: 4 }}
        render={({ field }) => (
          <OtpInput
            length={4}
            value={field.value}
            onChange={field.onChange}
            ref={field.ref}
          />
        )}
      />
      <button type="submit">Submit</button>
    </form>
  );
}

Development

# Install dependencies
npm install

# Start Storybook
npm run storybook

# Build
npm run build

# Run tests
npm test

License

MIT