React component for entering PIN codes.
Live demo at https://react-pin-field.soywod.me.
yarn add react-pin-field
# or
npm install react-pin-field
import PinField from "react-pin-field"
type PinFieldProps = {
ref?: React.Ref<HTMLInputElement[]>
length?: number
validate?: string | string[] | RegExp | ((key: string) => boolean)
format?: (char: string) => string
onResolveKey?: (key: string, ref?: HTMLInputElement) => any
onRejectKey?: (key: string, ref?: HTMLInputElement) => any
onChange?: (code: string) => void
onComplete?: (code: string) => void
} & React.InputHTMLAttributes<HTMLInputElement>
const defaultProps = {
ref: {current: []},
length: 5,
validate: /^[a-zA-Z0-9]$/,
format: key => key,
onResolveKey: () => {},
onRejectKey: () => {},
onChange: () => {},
onComplete: () => {},
}
You can control each inputs with the PIN field ref:
<PinField ref={ref} />
// Reset all inputs
ref.current.forEach(input => (input.value = ""))
// Focus one particular input
ref.current[2].focus()
React PIN Field can be styled either with className
or style
. You can also use pseudo-classes :nth-of-type
, :focus
, :hover
, :valid
, :invalid
β¦
The classes -{index}
, -focus
, -success
and -error
have been deprecated
(and are not used anymore) since the
v1.1.0
.
Length of the code (number of characters to type). Default: 5
.
The validator prop can be:
- A string of allowed characters:
abcABC123
- A list of allowed chars:
["a", "b", "c", "1", "2", "3"]
- A RegExp:
/^[a-zA-Z0-9]$/
- A function:
(char: string) => boolean
Function called just before adding a new char to the code. For example, to set
the code to upper case: (char: string) => char.toUpperCase()
- onResolveKey: called when a char passes successfully the
validate
function - onRejectKey: the opposite of
onResolveKey
- onChange: called when the code changes
- onComplete: called when the code has been fully filled
See the live demo.
git clone https://github.com/soywod/react-pin-field.git
cd react-pin-field
yarn install
To start the development server:
yarn start
To build the lib:
yarn build
To build the demo:
yarn build:demo
Unit tests are handled by Jest (.test
files) and
Enzyme (.spec
files).
yarn test:unit
End-to-end tests are handled by Cypress (.e2e
files).
yarn start
yarn test:e2e