### Install Dependencies Source: https://github.com/guilhermerodz/input-otp/blob/master/CLAUDE.md Installs all project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Install input-otp with npm Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/QUICK_START.md Install the input-otp package using npm. This command should be run in your project's root directory. ```bash npm install input-otp ``` -------------------------------- ### Development Mode Source: https://github.com/guilhermerodz/input-otp/blob/master/CLAUDE.md Starts the development server for all packages. ```bash pnpm dev ``` -------------------------------- ### Run Development Server Source: https://github.com/guilhermerodz/input-otp/blob/master/apps/website/README.md Use one of these commands to start the development server. Open http://localhost:3000 to view the app. ```bash npm run dev ``` ```bash yarn dev ``` ```bash pnpm dev ``` ```bash bun dev ``` -------------------------------- ### Usage Example for SlotProps Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/types.md Example of how to use the SlotProps interface to render an individual OTP slot. It conditionally applies styling based on `isActive` and displays the character or placeholder. ```tsx function Slot({ char, isActive, hasFakeCaret, placeholderChar }: SlotProps) { return (
{char ?? placeholderChar} {hasFakeCaret &&
|
}
) } ``` -------------------------------- ### Run Development Server Source: https://github.com/guilhermerodz/input-otp/blob/master/apps/playground/README.md Use these commands to start the development server for the Next.js project. Open http://localhost:3000 in your browser to view the application. ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` -------------------------------- ### Default OTP Input Example with Tailwind CSS Source: https://github.com/guilhermerodz/input-otp/blob/master/README.md A comprehensive example demonstrating the OTPInput component with Tailwind CSS, @shadcn/ui, tailwind-merge, and clsx. It includes custom Slot, FakeCaret, and FakeDash components for enhanced UI. ```tsx 'use client' import { OTPInput, SlotProps } from 'input-otp' ( <>
{slots.slice(0, 3).map((slot, idx) => ( ))}
{slots.slice(3).map((slot, idx) => ( ))}
)} /> // Feel free to copy. Uses @shadcn/ui tailwind colors. function Slot(props: SlotProps) { return (
{props.char ?? props.placeholderChar}
{props.hasFakeCaret && }
) } // You can emulate a fake textbox caret! function FakeCaret() { return (
) } // Inspired by Stripe's MFA input. function FakeDash() { return (
) } // tailwind.config.ts for the blinking caret animation. const config = { theme: { extend: { keyframes: { 'caret-blink': { '0%,70%,100%': { opacity: '1' }, '20%,50%': { opacity: '0' }, }, }, animation: { 'caret-blink': 'caret-blink 1.2s ease-out infinite', }, }, }, } // Small utility to merge class names. import { clsx } from 'clsx' import { twMerge } from 'tailwind-merge' import type { ClassValue } from 'clsx' export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } ``` -------------------------------- ### Basic Usage Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/README.md Demonstrates how to install and use the OTPInput component for basic OTP input functionality. ```APIDOC ## Installation ```bash npm install input-otp ``` ## Basic Usage ```tsx 'use client' import { OTPInput } from 'input-otp' function OTPForm() { return ( (
{slots.map((slot, idx) => (
{slot.char}
))}
)} /> ) } ``` ``` -------------------------------- ### Playground Development Mode Source: https://github.com/guilhermerodz/input-otp/blob/master/CLAUDE.md Starts the development server specifically for the playground application. ```bash pnpm dev:playground ``` -------------------------------- ### Complete Validation Example with Server-Side Check Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/input-validation.md An advanced example showing custom validation logic within `handleChange` and asynchronous server-side verification in `handleComplete`. Errors are managed and displayed to the user. ```tsx function AdvancedValidation() { const [value, setValue] = useState('') const [errors, setErrors] = useState([]) const validate = (newValue: string) => { const errs: string[] = [] if (newValue.length > 0 && !/^\\d+$/.test(newValue)) { errs.push('Only digits allowed') } if (newValue.length === 6) { // Additional validation for complete OTP if (newValue === '000000') { errs.push('Invalid OTP pattern') } } setErrors(errs) return errs.length === 0 } const handleChange = (newValue: string) => { if (validate(newValue)) { setValue(newValue) } } const handleComplete = async (otp: string) => { // Server-side validation try { const res = await fetch('/verify-otp', { method: 'POST', body: JSON.stringify({ otp }) }) if (!res.ok) { setErrors(['Invalid or expired OTP']) } } catch (err) { setErrors(['Verification failed']) } } return (
(
{slots.map((slot, idx) => (
{slot.char}
))}
)} /> {errors.length > 0 && (
{errors.map((err, idx) => (

• {err}

))}
)} {value.length === 6 && errors.length === 0 && (

✓ Valid OTP format

)}
) } ``` -------------------------------- ### OTPInputContext Usage Example Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/exports.md Demonstrates how to consume OTPInputContext within a component to access render props and how to nest a custom component within OTPInput. ```typescript function MyComponent() { const renderProps = useContext(OTPInputContext) return
{renderProps.slots.map(...)}
} ``` -------------------------------- ### Advanced Slot Rendering with Context Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/OTPInputContext.md An advanced example showcasing how to use OTPInputContext for custom slot rendering, including active states and placeholder characters. ```APIDOC ### Example: Advanced Slot Rendering with Context ```tsx 'use client' import { OTPInput, OTPInputContext, SlotProps } from 'input-otp' import { useContext } from 'react' function OTPForm() { return ( ) } function SlotGrid() { const { slots, isFocused, isHovering } = useContext(OTPInputContext) return (
{slots.map((slot, idx) => ( ))}
) } function SlotItem({ slot, isActive }: { slot: SlotProps; isActive: boolean }) { return (
{slot.char ? ( ) : ( {slot.placeholderChar} )} {slot.hasFakeCaret && }
) } function FakeCaret() { return (
) } ``` ``` -------------------------------- ### Zustand State Management for OTP Input Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/form-integration.md Integrate OTPInput with Zustand for simple state management. This example uses a store to manage the OTP value. ```tsx import { OTPInput, REGEXP_ONLY_DIGITS } from 'input-otp' import { create } from 'zustand' const useOTPStore = create((set) => ({ otp: '', setOTP: (value: string) => set({ otp: value }), clearOTP: () => set({ otp: '' }) })) function OTPWithZustand() { const { otp, setOTP } = useOTPStore() return ( (
{slots.map((slot, idx) => (
{slot.char}
))}
)} /> ) } ``` -------------------------------- ### Basic Paste Transformation Example Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/input-validation.md This example demonstrates removing hyphens from pasted text using pasteTransformer. It ensures that only digits are accepted by the OTP input. ```tsx import { OTPInput, REGEXP_ONLY_DIGITS } from 'input-otp' function OTPWithPaste() { return ( text.replaceAll('-', '')} render={({ slots }) => (
{slots.map((slot, idx) => (
{slot.char}
))}
)} /> ) } ``` -------------------------------- ### Usage Example for RenderProps Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/types.md Example of a custom render function using RenderProps to display OTP slots. The `renderFn` receives slot states and focus/hover information to customize the input's appearance. ```tsx const renderFn = (props: RenderProps) => { const { slots, isFocused, isHovering } = props return (
{slots.map((slot, idx) => (
{slot.char || slot.placeholderChar}
))}
) } ``` -------------------------------- ### Basic OTPInput with TypeScript Types Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/QUICK_START.md Demonstrates how to import and use the OTPInput component with TypeScript, including defining props and a custom render function for slots. Ensure you have the 'input-otp' package installed. ```tsx import { OTPInput, type OTPInputProps, type SlotProps, type RenderProps } from 'input-otp' const props: OTPInputProps = { maxLength: 6, render: ({ slots, isFocused }: RenderProps) => (
{slots.map((slot: SlotProps) => (
{slot.char}
))}
) } ``` -------------------------------- ### OTP Pattern Validation Examples Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/QUICK_START.md Use the `pattern` prop to define allowed characters for OTP input. Examples include digits only, letters only, alphanumeric, and custom regex patterns. ```tsx // Digits only pattern={REGEXP_ONLY_DIGITS} ``` ```tsx // Letters only pattern={REGEXP_ONLY_CHARS} ``` ```tsx // Alphanumeric pattern={REGEXP_ONLY_DIGITS_AND_CHARS} ``` ```tsx // Custom pattern pattern="^[A-F0-9]+"$ ``` -------------------------------- ### OTPInput with Pattern Validation Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/OTPInput.md This example demonstrates how to use OTPInput with a specific pattern, such as only allowing digits. The `pattern` prop accepts a regular expression for validation. ```tsx import { OTPInput, REGEXP_ONLY_DIGITS } from 'input-otp' function NumericOTP() { return ( (
{slots.map((slot, idx) =>
{slot.char}
)}
)} /> ) } ``` -------------------------------- ### Minimal OTP Input Form Example Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/QUICK_START.md A basic React component demonstrating how to use OTPInput for a 6-digit OTP input. It renders read-only input fields for each digit. ```tsx 'use client' import { OTPInput } from 'input-otp' export default function OTPForm() { return ( (
{slots.map((slot, idx) => ( ))}
)} /> ) } ``` -------------------------------- ### OTPInput using Context API Pattern Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/OTPInput.md This example shows how to use the `OTPInputContext` to access slot information and focus state within child components. This pattern is useful for complex custom rendering. ```tsx 'use client' import { OTPInput, OTPInputContext } from 'input-otp' import { useContext } from 'react' function OTPForm() { return ( ) } function SlotContainer() { const { slots, isFocused } = useContext(OTPInputContext) return (
{slots.map((slot, idx) => (
{slot.char}
))}
) } ``` -------------------------------- ### OTP Input with Placeholder Characters Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/QUICK_START.md Display placeholder characters in empty OTP slots using the `placeholder` prop. This example uses dots as placeholders. ```tsx import { OTPInput } from 'input-otp' export default function WithPlaceholder() { return ( (
{slots.map((slot, idx) => (
{slot.char ?? slot.placeholderChar}
))}
)} /> ) } ``` -------------------------------- ### OTP Input with Placeholder Rendering Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/slot-rendering.md Demonstrates configuring an OTP input with a placeholder string and using the `render` prop to display either the character or the placeholder character for each slot. This is useful for guiding user input. ```tsx (
{slots.map((slot, idx) => (
{slot.char ?? slot.placeholderChar ?? ''}
))}
)} /> ``` -------------------------------- ### Displaying OTP Status with Context Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/OTPInputContext.md Example of a component that reads OTP slot count and focus state from the context to display user-friendly status messages. ```tsx function StatusDisplay() { const { slots, isFocused } = useContext(OTPInputContext) const filledCount = slots.filter(s => s.char !== null).length return (

{filledCount}/{slots.length} digits entered

{isFocused ? 'Focused' : 'Not focused'}

) } ``` -------------------------------- ### Redux State Management for OTP Input Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/form-integration.md Integrate OTPInput with Redux for centralized state management. This example assumes you have a Redux store configured with an 'otpSlice'. ```tsx import { OTPInput, REGEXP_ONLY_DIGITS } from 'input-otp' import { useDispatch, useSelector } from 'react-redux' import { setOTP } from './otpSlice' function OTPWithRedux() { const dispatch = useDispatch() const otp = useSelector((state) => state.otp.value) return ( dispatch(setOTP(value))} pattern={REGEXP_ONLY_DIGITS} render={({ slots }) => (
{slots.map((slot, idx) => (
{slot.char}
))}
)} /> ) } ``` -------------------------------- ### Multi-Format Support with Paste Transformation Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/input-validation.md This example shows how to create a flexible paste transformer that handles multiple input formats, converts them to uppercase, removes non-alphanumeric characters, and limits the output to a specific length. ```tsx function FlexibleOTP() { const pasteTransformer = (text: string) => { // Remove all non-alphanumeric let cleaned = text.replace(/[^a-zA-Z0-9]/g, '') // Uppercase cleaned = cleaned.toUpperCase() // Take first 6 characters return cleaned.slice(0, 6) } return ( (
{slots.map((slot, idx) => (
{slot.char}
))}
)} /> ) } // Accepts: // - "AB-CD-EF" → "ABCDEF" // - "ab cd ef" → "ABCDEF" // - "abcdef" → "ABCDEF" // - "12-34-56" → "123456" ``` -------------------------------- ### Formik Integration for OTP Input Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/form-integration.md Use this snippet to integrate OTPInput with Formik for form handling and validation. Ensure Yup is installed for schema validation. ```tsx import { OTPInput, REGEXP_ONLY_DIGITS } from 'input-otp' import { Formik, Form } from 'formik' import * as Yup from 'yup' const validationSchema = Yup.object().shape({ otp: Yup.string() .required('OTP is required') .length(6, 'OTP must be 6 digits') .matches(/^\d+$/, 'OTP must contain only digits') }) function OTPWithFormik() { const handleSubmit = (values) => { console.log('OTP:', values.otp) } return ( {({ values, setFieldValue, errors }) => (
setFieldValue('otp', otp)} render={({ slots }) => (
{slots.map((slot, idx) => (
{slot.char}
))}
)} /> {errors.otp &&

{errors.otp}

} )}
) } ``` -------------------------------- ### OTP Input using Context API Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/QUICK_START.md Leverage the Context API for accessing OTP input state and methods within nested components. This example shows how `OTPInputContext` can be used. ```tsx import { OTPInput, OTPInputContext } from 'input-otp' import { useContext } from 'react' export default function ContextExample() { return ( ) } function SlotDisplay() { const { slots, isFocused } = useContext(OTPInputContext) return (
{slots.map((slot, idx) => (
{slot.char}
))}
) } ``` -------------------------------- ### Handle Standard Keyboard Events with onKeyDown Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/events-and-refs.md The component supports standard HTML input events, including `onKeyDown`. This example demonstrates how to trigger an action, like form submission, when the 'Enter' key is pressed. ```tsx < OTPInput maxLength={6} onKeyDown={(e) => { if (e.key === 'Enter') { submitForm() } }} render={({ slots }) => ...} /> ``` -------------------------------- ### Set Selection Range on OTP Input Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/events-and-refs.md Demonstrates how to programmatically set the selection range within the OTP input using the `.setSelectionRange` method accessed via the ref. This example selects all text. ```tsx ``` -------------------------------- ### OTP Input with Auto-Submit on Complete Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/QUICK_START.md This example demonstrates how to automatically submit a form when the OTP input is completed. It uses `useRef` to access the form element and `onComplete` callback. ```tsx import { OTPInput, REGEXP_ONLY_DIGITS } from 'input-otp' import { useRef } from 'react' export default function AutoSubmitOTP() { const formRef = useRef(null) return (
formRef.current?.submit()} render={({ slots }) => (
{slots.map((slot, idx) => (
{slot.char}
))}
)} /> ) } ``` -------------------------------- ### Async OTP Submission with Loading State Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/form-integration.md Handle asynchronous OTP submission by integrating with a fetch API call. This example shows how to manage loading and success states to provide user feedback during the verification process. ```tsx import { OTPInput, REGEXP_ONLY_DIGITS } from 'input-otp' import { useState } from 'react' function AsyncOTPSubmission() { const [otp, setOTP] = useState('') const [isLoading, setIsLoading] = useState(false) const [success, setSuccess] = useState(false) const handleComplete = async (value: string) => { setIsLoading(true) try { const response = await fetch('/api/verify-otp', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ otp: value }) }) if (response.ok) { setSuccess(true) } } catch (error) { console.error('OTP verification failed:', error) } finally { setIsLoading(false) } } return (
(
{slots.map((slot, idx) => (
{slot.char}
))}
)} /> {isLoading &&

Verifying...

} {success &&

OTP verified!

}
) } ``` -------------------------------- ### Controlled Input with Render Prop Example Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/OTPInput.md Demonstrates a controlled OTP input using the render prop pattern. It manages the input value with React's useState hook and customizes the appearance of each OTP slot. ```tsx 'use client' import { OTPInput, SlotProps } from 'input-otp' import { useState } from 'react' function OTPForm() { const [value, setValue] = useState('') return ( console.log('OTP complete:', value)} render={({ slots, isFocused }) => (
{slots.map((slot, idx) => ( ))}
)} /> ) } function Slot({ char, isActive, hasFakeCaret, isFocused }) { return (
{char} {hasFakeCaret && |}
) } ``` -------------------------------- ### Advanced OTP Slot Rendering with State Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/slot-rendering.md Shows advanced rendering by utilizing all state properties from `RenderProps` and `SlotProps`. This example customizes slot appearance based on `isActive`, `char`, `placeholderChar`, and `hasFakeCaret` states, and also applies styles based on `isFocused` and `isHovering` states of the input. ```tsx function AdvancedOTP() { return ( (
{slots.map((slot, idx) => ( ))}
)} /> ) } function SlotComponent({ slot }: { slot: SlotProps }) { return (
{slot.char && {slot.char}} {!slot.char && slot.placeholderChar && ( {slot.placeholderChar} )} {slot.hasFakeCaret && }
) } function FakeCaret() { return (
) } ``` -------------------------------- ### Get Current OTP Value Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/events-and-refs.md Provides an example of how to retrieve the current value from the OTP input using its ref. This is useful for form submissions or validation. ```tsx const handleSubmit = () => { const otp = inputRef.current?.value console.log('Current OTP:', otp) } ``` -------------------------------- ### Build All Packages Source: https://github.com/guilhermerodz/input-otp/blob/master/CLAUDE.md Builds all packages in the monorepo using Turbo. ```bash pnpm build ``` -------------------------------- ### Format Code Source: https://github.com/guilhermerodz/input-otp/blob/master/CLAUDE.md Applies Prettier formatting to the entire project according to the defined configuration. ```bash pnpm format ``` -------------------------------- ### Import OTPInputContext Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/OTPInputContext.md Import the OTPInputContext from the 'input-otp' library. ```typescript import { OTPInputContext } from 'input-otp' ``` -------------------------------- ### Checksum Validation for OTP Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/input-validation.md Implement custom checksum logic to validate the OTP. This example calculates the sum of digits and checks if it's even. ```tsx const validateChecksum = (otp: string) => { // Custom validation logic const sum = otp.split('').reduce((a, b) => a + parseInt(b), 0) return sum % 2 === 0 } if (validateChecksum(value)) { // Valid } ``` -------------------------------- ### Build Library Only Source: https://github.com/guilhermerodz/input-otp/blob/master/CLAUDE.md Builds only the core library package using tsup, outputting to the dist/ directory. ```bash pnpm build:lib ``` -------------------------------- ### Use OTPInput Component Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/exports.md Import and use the main OTP input component. Configure it with props like maxLength and a render function to customize its appearance. ```typescript import { OTPInput } from 'input-otp' ...} /> ``` -------------------------------- ### Use Context Props for Rendering Source: https://github.com/guilhermerodz/input-otp/blob/master/README.md Import `OTPInputContext` and use `React.useContext` to access slots for custom rendering, replacing the `render` prop. ```diff +import { OTPInputContext } from 'input-otp' function MyForm() { return ( ) } +function OTPInputWrapper() { + const inputContext = React.useContext(OTPInputContext) + return ( + <> + {inputContext.slots.map((slot, idx) => ( + + ))} + + ) +} ``` -------------------------------- ### Basic OTP Slot Rendering Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/slot-rendering.md Demonstrates basic rendering of OTP slots using the `render` prop. It maps over the `slots` array to display each character in a styled div. ```tsx import { OTPInput } from 'input-otp' function BasicOTP() { return ( (
{slots.map((slot, idx) => (
{slot.char}
))}
)} /> ) } ``` -------------------------------- ### Automatic Form Submission on OTP Completion Source: https://github.com/guilhermerodz/input-otp/blob/master/README.md Submit the form automatically when the OTP is completed. This example shows how to use the `onComplete` prop to trigger form submission. ```tsx export default function Page() { const formRef = useRef(null) const buttonRef = useRef(null) return (
formRef.current?.submit()} // ... or focus the button like as you wish onComplete={() => buttonRef.current?.focus()} /> ) } ``` -------------------------------- ### Basic Ref Usage with useRef Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/events-and-refs.md Demonstrates how to initialize a ref using `useRef` and assign it to the OTPInput component to access the underlying HTMLInputElement. ```typescript const inputRef = useRef(null) ...} /> ``` -------------------------------- ### OTP Input Integration with react-hook-form Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/QUICK_START.md Integrate OTP input with `react-hook-form` for streamlined form handling. This example shows how to register the OTP input and use `handleSubmit`. ```tsx import { OTPInput, REGEXP_ONLY_DIGITS } from 'input-otp' import { useForm } from 'react-hook-form' export default function OTPWithHookForm() { const { register, handleSubmit, watch } = useForm({ defaultValues: { otp: '' } }) const otp = watch('otp') return (
console.log(data))}> (
{slots.map((slot, idx) => (
{slot.char}
))}
)} /> ) } ``` -------------------------------- ### Custom Pattern: Only digits with hyphens Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/regexp-patterns.md Example of using a custom pattern to allow digits and hyphens. The pattern is anchored and requires at least one digit or hyphen. ```tsx ...} /> ``` -------------------------------- ### OTPInputContext Usage Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/OTPInputContext.md Demonstrates how to import and use the OTPInputContext within a React component to access slot and input states. ```APIDOC ## Import ```typescript import { OTPInputContext } from 'input-otp' ``` ## Usage Use `useContext()` to access the value within children of `OTPInput`: ```typescript import { useContext } from 'react' const context = useContext(OTPInputContext) ``` ## Value Type The context provides a `RenderProps` object containing: | Property | Type | Description | |----------|------|-------------| | slots | `SlotProps[]` | Array of slot state objects, one per maxLength position. | | isFocused | `boolean` | Whether the underlying input element is currently focused. | | isHovering | `boolean` | Whether the user is hovering over the input container (false if input is disabled). | ### Example: Basic Context Usage ```tsx 'use client' import { OTPInput, OTPInputContext } from 'input-otp' import { useContext } from 'react' function OTPForm() { return ( ) } function SlotDisplay() { const { slots, isFocused } = useContext(OTPInputContext) return (
{slots.map((slot, idx) => (
{slot.char}
))}
) } ``` ``` -------------------------------- ### REGEXP_ONLY_DIGITS Pattern Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/regexp-patterns.md Use this pattern to match inputs containing only numeric digits (0-9). It is anchored to the start and end of the string and requires at least one digit. ```typescript import { REGEXP_ONLY_DIGITS } from 'input-otp' // Value: '^\d+$' ``` ```tsx import { OTPInput, REGEXP_ONLY_DIGITS } from 'input-otp' function NumericOTP() { return ( (
{slots.map((slot, idx) => (
{slot.char}
))}
)} /> ) } ``` -------------------------------- ### Grouped OTP Slots Example Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/QUICK_START.md Customize the visual grouping of OTP slots, for instance, to display them like '123-456'. This involves slicing the `slots` array in the `render` prop. ```tsx import { OTPInput, REGEXP_ONLY_DIGITS } from 'input-otp' export default function GroupedOTP() { return ( (
-
)} /> ) } function Group({ slots }: { slots: any[] }) { return (
{slots.map((slot, idx) => (
{slot.char}
))}
) } ``` -------------------------------- ### Dynamic Import of OTPInput Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/exports.md Demonstrates how to dynamically import the OTPInput component using a dynamic import statement. This can be useful for code-splitting and lazy loading. ```typescript const { OTPInput } = await import('input-otp') ``` -------------------------------- ### Import OTPInput Component in React Source: https://github.com/guilhermerodz/input-otp/blob/master/README.md Import the OTPInput component from the 'input-otp' library. Ensure to include the 'use client' directive for server components. ```diff +'use client' +import { OTPInput } from 'input-otp' ``` -------------------------------- ### Style OTPInput with CSS Modules Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/QUICK_START.md Apply styles using CSS Modules by importing a stylesheet and referencing its classes. Conditional styling for active slots is handled via class toggling. ```tsx import styles from './otp.module.css' (
{slots.map((slot, idx) => (
{slot.char}
))}
)} /> ``` -------------------------------- ### Blacklist Validation for OTP Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/input-validation.md Prevent specific, known invalid OTP patterns from being used. This example checks if the input value is present in a predefined list of blocked patterns. ```tsx const blockedPatterns = ['000000', '111111', '123456'] if (!blockedPatterns.includes(value)) { // Not blocked } ``` -------------------------------- ### OTP Input with Paste Transformation Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/configuration.md Customize how pasted text is transformed before being applied to the OTP input. This example converts pasted text to uppercase and removes hyphens and spaces. ```tsx import { OTPInput } from 'input-otp' function OTPWithPaste() { return ( text .toUpperCase() .replaceAll('-', '') .replaceAll(' ', '') } render={({ slots }) => (
{slots.map((s, i) =>
{s.char}
)}
)} /> ) } ``` -------------------------------- ### Custom Pattern: Uppercase letters only Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/regexp-patterns.md Example of using a custom pattern to allow only uppercase alphabetic characters. The pattern is anchored and requires at least one uppercase letter. ```tsx ...} /> ``` -------------------------------- ### OTP Input with Context API Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/slot-rendering.md Demonstrates using the Context API to access OTP input slots and focus state for rendering. This is useful for deeply nested components or when preferring the Context API pattern. ```typescript import { OTPInput, OTPInputContext } from 'input-otp' import { useContext } from 'react' function OTPForm() { return ( ) } function SlotGrid() { const { slots, isFocused } = useContext(OTPInputContext) return (
{slots.map((slot, idx) => ( ))}
) } ``` -------------------------------- ### Controlled Component Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/README.md Illustrates how to use OTPInput as a controlled component, managing its value and handling completion events. ```APIDOC ## Controlled Component ```tsx import { OTPInput, REGEXP_ONLY_DIGITS } from 'input-otp' import { useState } from 'react' function ControlledOTP() { const [value, setValue] = useState('') const handleComplete = (otp: string) => { console.log('OTP completed:', otp) } return ( (
{slots.map((slot, idx) => (
{slot.char}
))}
)} /> ) } ``` ``` -------------------------------- ### OTP Input with Paste Transformer Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/QUICK_START.md Customize paste behavior using `pasteTransformer` to clean up pasted text before it populates the OTP fields. This example removes hyphens from pasted text. ```tsx import { OTPInput, REGEXP_ONLY_DIGITS } from 'input-otp' export default function WithPasteTransform() { return ( text.replaceAll('-', '')} render={({ slots }) => (
{slots.map((slot, idx) => (
{slot.char}
))}
)} /> ) } ``` -------------------------------- ### Basic OTP Input with Context Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/OTPInputContext.md Demonstrates a basic OTP input form where child components access context to display slots and focus state. ```tsx 'use client' import { OTPInput, OTPInputContext } from 'input-otp' import { useContext } from 'react' function OTPForm() { return ( ) } function SlotDisplay() { const { slots, isFocused } = useContext(OTPInputContext) return (
{slots.map((slot, idx) => (
{slot.char}
))}
) } ``` -------------------------------- ### Clear OTP Input Programmatically Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/events-and-refs.md Illustrates how to clear the OTP input's value and then focus it using the ref. This example demonstrates direct manipulation of the input's `.value` property. ```tsx ``` -------------------------------- ### Run Playwright Tests with UI Source: https://github.com/guilhermerodz/input-otp/blob/master/CLAUDE.md Runs Playwright tests in a headed mode with a user interface for visualization. ```bash pnpm test:ui ``` -------------------------------- ### Custom Pattern: Special characters allowed Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/api-reference/regexp-patterns.md Example of using a custom pattern to allow digits and specific special characters. The pattern is anchored and requires at least one allowed character. ```tsx ...} /> ``` -------------------------------- ### Import input-otp with Alias Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/exports.md Shows how to import the OTPInput component and assign it an alias for brevity in your JSX. This is useful for reducing boilerplate in your code. ```typescript import { OTPInput as OTP } from 'input-otp' ...} /> ``` -------------------------------- ### Metadata Tracking for Cursor Movement Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/internals.md Tracks the previous selection state (start, end, direction) to determine cursor movement direction. Uses a useRef to persist state across renders. ```typescript const inputMetadataRef = useRef({ prev: [ inputRef.current?.selectionStart, inputRef.current?.selectionEnd, inputRef.current?.selectionDirection, ], }) ``` -------------------------------- ### Tsup Build Configuration Source: https://github.com/guilhermerodz/input-otp/blob/master/_autodocs/internals.md Command-line configuration for the tsup build tool. This command enables TypeScript definition file generation and code minification for the library. ```bash tsup --dts --minify ``` -------------------------------- ### Paste Transformer for Hyphenated Input Source: https://github.com/guilhermerodz/input-otp/blob/master/README.md Use the `pasteTransformer` prop to handle pasted text that may not conform to the input's regex or max length. This example removes hyphens from pasted text. ```tsx pasted.replaceAll('-', '')} /> ```