Skip to main content

React otp input hook

React OTP Input Hook

npm npm NPM Coverage Status Build Status

A simple react hook to create otp inputs with ease. Inspired by libraries like react-hook-form, downshift-js ...etc

Features

  • No dependencies (only needs react as peer dependency)
  • Small size
  • Easy to use
  • Does not come with any styling so you are free to use any input component of your own. (refs need to be forwarded)
  • Written in typescript
  • Lots of options
  • Works with many libraries

Installation

npm install react-otp-input-hook

Basic Usage


import React from "react";
import { useOtpInput } from "react-otp-input-hook";

export default App = () => {
const { register } = useOtpInput({
onInputValueChange: (value) => {
console.log(value)
},
defaultInlineStyles: {
height: '40px',
width: '40px',
margin: '0 5px',
textAlign: 'center',
fontSize: '20px'
},
placeholder: '-'
});

const defaultOptions = { required: true };

return (
<div>
<input {...register("digit-1", defaultOptions)} />
<input {...register("digit-2", defaultOptions)} />
<input {...register("digit-3", defaultOptions)} />
<input {...register("digit-4", defaultOptions)} />
<input {...register("digit-5", defaultOptions)} />
</div>
);
};

Output

Basic version with loop

import React  from "react";
import { useOtpInput } from "react-otp-input-hook";

export default App = () => {
const { inputs } = useOtpInput({
numberOfInputs: 5, // do not forget this
onInputValueChange: (value) => {
console.log(value)
},
defaultInlineStyles: {
height: '40px',
width: '40px',
margin: '0 5px',
textAlign: 'center',
fontSize: '20px'
},
placeholder: '-'
});

return (
<div>
{inputs.map((input, i) => {
return <input required key={i} {...input} />;
})}
</div>
);
};

Output

Use it inside any form

import React from "react";
import { useOtpInput } from "react-otp-input-hook";
import "./styles.css";

export const OTPForm = () => {
const { register, value, inputs } = useOtpInput({
placeholder: "-",
numberOfInputs: 5,
});


return (
<div>
<form
className="basic-otp-form"
onSubmit={(e) => {
e.preventDefault();
alert(value);
}}
>
<div className="otp">
{inputs.map((input, i) => {
return <input required key={i} {...input} />;
})}
</div>

<button type="submit">Submit</button>
</form>

<div>Value: {value}</div>
</div>
);
};

Output

Value: