JSPM

  • Created
  • Published
  • Downloads 21928
  • Score
    100M100P100Q142906F
  • License BSD-3-Clause

React component for entering PIN codes

Package Exports

  • react-pin-field
  • react-pin-field/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (react-pin-field) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

📟 React PIN Field

npm

React PIN Field is a React wrapper for PIN Field, a native web component for entering PIN codes.

gif

Live demo at https://soywod.github.io/pin-field/demo/.

Installation

npm install react react-dom @soywod/pin-field react-pin-field
# or
yarn add react react-dom @soywod/pin-field react-pin-field

Usage

import ReactPinField from "react-pin-field"

Props

type ReactPinFieldProps = {
  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: ReactPinFieldProps = {
  length: 5,
  validate: /^[a-zA-Z0-9]$/,
  format: key => key,
  onResolveKey: () => {},
  onRejectKey: () => {},
  onChange: () => {},
  onComplete: () => {},
}

Ref

You can access the PIN field web component via the ref:

<ReactPinField ref={ref} />

// Reset all inputs
ref.current.inputs.forEach(input => (input.value = ""))

// Focus one particular input
ref.current.inputs[2].focus()

Style

React PIN Field can be styled either with className or style. You can also use pseudo-classes :nth-of-type, :focus, :hover, :valid, :invalid

Length

Length of the code (number of characters to type). Default: 5.

Validate

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

Format

The formatter allows you to format the code. For example, to set the code to upper case: (char: string) => char.toUpperCase()

Events

  • onResolveKey: triggered when a char passes successfully the validator
  • onRejectKey: the opposite of onResolveKey
  • onChange: triggered when the code changes
  • onComplete: triggered when the code has been completed

Development

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

Sponsoring

github paypal ko-fi buy-me-a-coffee liberapay