OTP Input
Accessible one-time password component with copy paste functionality
About
OTP Input is built on top of the react-otp-input API and has been modified to suit the styles and needs of Shadcn. For more information on the original package, please refer to the documentation.
Installation
npx shadcn-ui@latest add otp-input
Usage
import { OTPInput } from '@/components/ui/otp-input';
<OTPInput />
Examples
Basic Usage
With custom number inputs
You can customize the number of inputs by passing the numInputs
prop.
With custom placeholder
By default the placeholder is _
. You can customize it by passing the placeholder
prop.
With separator
Sometimes you may need to have a separator between each generated input. For this case we have the renderSeparator
prop.
Controlling the value
You can control the value of the OTP input by passing the value
and onChange
props.
OTP Value: 123456
Detecting onPaste event
You can detect the onPaste
event by passing the onPaste
prop.
Auto focus
You can set the autoFocus
prop to true
to automatically focus the first input.
For practical purposes, we did not generate a live example for this case to avoid scrolling the page to this point because of the autoFocus
import { OTPInput } from "@/components/ui/otp-input";
export default function OtpInputDemo() {
return <OTPInput autoFocus />
}
With Form
You can use the OTPInput component with the Form component.
With Server Actions
The component renders by default this line of code
<input type="hidden" id={id} name={name} value={otpValue} />
This allows to have a hidden input for the form you use with server actions and you can capture it inside the FormData. It is important that you set the name
prop to be included inside the FormData.