0.2.0 • Published 1 year ago

react-confirmation-code-input v0.2.0

Weekly downloads
2
License
MIT
Repository
github
Last release
1 year ago

Contributors Forks Stargazers Issues MIT License LinkedIn

About The Project

This library provides a hook that lets you write a confirmation code input component while the library manages the refs and some interactions like focusing the next input element when an input has been entered. It can thus be considered headless.

The library also provides you with a component implemented on top of that hook. It lets you override the input and container elements' styling by passing respective class names of your choice as properties to the component.

Getting Started

Prerequisites

This is a react library primarily providing a headles react hook for you to implement your own confirmation code input whilst delegating the handling of the element refs and some of the behaviour to said hook. You therefore need a react version as a peer dependency that has support for hooks i.e. any version of react >= 16.8.

Installation

NPM

npm install react-confirmation-code-input

Yarn

yarn add react-confirmation-code-input

PNPM

pnpm add react-confirmation-code-input

Usage

Usage utilizing the hook

import * as React from 'react';
import { useConfirmationCodeInput } from 'react-confirmation-code-input';
import './style.css';

export default function App() {
  const {
    refs,
    value: inputs,
    clear,
    setFocus,
    reset,
    inputProps,
  } = useConfirmationCodeInput({
    length: 5,
    allowedPattern: 'numeric',
    initialValue: '01234',
    autoFocus: true,
  });

  // reset and setFocus take optional params so we can't pass them directly
  // to onClick but have to eliminate the optional parameter first
  const onReset = React.useCallback(() => reset(), []);
  const onSetFocus = React.useCallback(() => setFocus(), []);

  return (
    <main>
      <div className="input-container">
        {refs.map((ref, index) => (
          <input key={index} value={inputs[index]} ref={ref} {...inputProps} />
        ))}
      </div>
      <div className="button-box">
        <button onClick={onReset}>Reset</button>
        <button onClick={clear}>Clear</button>
        <button onClick={onSetFocus}>Focus</button>
      </div>
    </main>
  );
}

Open in StackBlitz

Using the provided Component

import * as React from 'react';
import {
  ConfirmationCodeInput,
  ConfirmationCodeInputHandles as Handles,
} from 'react-confirmation-code-input';
import './style.css';

export default function App() {
  const handlesRef = React.useRef<Handles>(null);
  const { reset, clear, setFocus } = React.useMemo(
    () => ({
      reset: () => handlesRef.current.reset(),
      clear: () => handlesRef.current.clear(),
      setFocus: () => handlesRef.current.setFocus(),
    }),
    []
  );

  return (
    <main>
      <ConfirmationCodeInput
        ref={handlesRef}
        length={5}
        allowedPattern="numeric"
        autoFocus
        initialValue="01234"
      />
      <div className="button-box">
        <button onClick={reset}>Reset</button>
        <button onClick={clear}>Clear</button>
        <button onClick={setFocus}>Focus</button>
      </div>
    </main>
  );
}

Open in StackBlitz

API

hook version

The hook takes an object as parameter and returns an object as a result:

useConfirmationCodeInput(options: UseConfirmationCodeInputProps) => UseConfirmationCodeInputResult

UseConfirmationCodeInputProps:

allowedPattern?: AllowedPattern;
autoFocus?: boolean;
useValueHook?: UseValue;
initialValue?: string;
length: number;
onChange?: (value: string) => void;
ParameterDescriptionTypeRequiredDefault
allowedPatternAccepted patternAllowedPatternno"numeric"
useValueHookThe hook to store and modify the input valueUseValueno
autoFocuswheter to put focus on first input upon mountingbooleannotrue
initialValueInitial value as stringstringno
lengthNumber of individual inputsnumberyes
onChangemethod called when the value changes(value: string) => voidno

AllowedPattern:

Allowed Pattern is either one of the predefined patterns "numeric" | "alpha" | "alphanumeric", a RegExp or a function with the following signature:

(input: string, index: number, value: string[]) => boolean

UseValue

Only provide this if you want to intercept/modify the input or the way it is stored. The signature is as follows:

(options: UseValueOptions) => [string[], Mutators];

UseValueOptions and Mutators are described below. You need to provide the same signature if you want to pass in a custom useValue parameter.

UseValueOptions:

An object of the shape { allowedPattern: AllowedPattern, length: number }:

PropertyDescription
allowedPatternThe pattern for valid inputs
lengthThe length of a valid code

Mutators:

An object of the shape:

{
    clear: () => void;
    reset: (value?: string) => void;
    update: (input: string, index: number, options: UpdateOptions) => void;
}
PropertyDescriptionType
clearA method to clear the value() => void
resetA method to reset the value to either the given value(value?: string) => void(truncated/filled to the correct length) if given or else to the initial value.
updateA method to update the value upon a given input character(input: string, index: number, options: UpdateOptions) => void

UseConfirmationCodeInputResult:

The result of calling useConfirmationCodeInput is an option adhering to the following interface:

    refs: Array<RefObject<HTMLInputElement>>;
    value: string[];
    reset: (value?: string) => void;
    clear: () => void;
    setFocus: (index?: number) => void;
    inputProps: {
        onFocus: FocusEventHandler<HTMLInputElement>;
        onKeyDown: KeyboardEventHandler<HTMLInputElement>;
        onPaste: ClipboardEventHandler<HTMLInputElement>;
        onInput: FormEventHandler<HTMLInputElement>;
    };
PropertyDescriptionType
refsAn array of refs each of which needs to be passed to the respective input elementArray<RefObject<HTMLInputElement>>
valueThe current value as a string array with each value comprising a single characterstring[]
resetsee Mutators(value?: string) => void
clearsee Mutators() => void
setFocussee Mutators(index?: number) => void
inputPropsThe object with properties that must be passed to each individual inputInputProps'

InputProps

The inputProps returned by the useConfirmationCodeInputResult hook are supposed to be spread into each of the input elements. They comprise needed event handlers on which the hook relies in order to react to user events.

PropertyDescriptionType
onFocusonFocus event handlerFocusEventHandler<HTMLInputElement>
onKeyDownonKeyDown event handlerKeyboardEventHandler<HTMLInputElement>
onPasteonPaste event handlerClipboardEventHandler<HTMLInputElement>
onInputonInput event handlerFormEventHandler<HTMLInputElement>

Component

The component takes the following parameters:

PropertyDescriptionTypeRequiredDefault
refreference to get access to the exposed MutatorsReact.MutableRefObjectno
lengthSee corresponding hook paramnumberyes
allowedPatternSee corresponding hook paramAllowedPatternnonumeric
initialValueSee corresponding hook paramstringno
onChangeSee corresponding hook param(value: string) => voidno
autoFocusSee corresponding hook parambooleanno
containerClsCSS class to be appended to the input container's class namesstringno
inputClsCSS class to be appended to the input's class namesstringno
disabledWhether the inputs are disabledbooleanno
isPasswordWhether the inputs are of type passwordbooleanno

License

Distributed under the MIT License. See LICENSE for more information.

Contact

Project Link: https://github.com/momesana/react-confirmation-code-input

0.1.0

1 year ago

0.2.0

1 year ago

0.1.1

1 year ago

1.0.0

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago