1.0.4 • Published 11 months ago

react-auth-code v1.0.4

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

React Auth Code

React component for entering and validating PIN code. With highly customizable renderInput prop, adjusting UI/UX more easily.

Install

$ npm install react-auth-code
# or
$ yarn add react-auth-code

Usage

Basic Usage

  • onChange: trigger when codes changed.
  • onComplete: trigger when codes length reach fields setting
import AuthCode from 'react-auth-code';

const App = () => {
  const [codes, setCodes] = useState<string[]>();

  const handleOnChange = (newCodes: string[]) => {
    setCodes(newCodes);
  };

  const handleOnComplete = (newCodes: string[]) => {
    // ... do something with completed newCodes
  };

  return (
    <AuthCode
      onChange={handleOnChange}
      onComplete={handleOnComplete}
    />
  );
};

export default App;

InputType & Validation

By default, inputType is tel, and only numbers 0-9 is allowed to be input. we can disable this by changing onlyNumber prop to false.

provide the custom validate function to validate the input value before changing value in each input field.

onlyNumber and validate is checked seperately, and onlyNumber will be checked before validate, so you can use onlyNumber, validate in the same time.

import { useState } from 'react';
import AuthCode from 'react-auth-code';

const App = () => {
  // ...
  return (
    <AuthCode
      inputType="tel"
      onlyNumber={false}
      // below same as "onlyNumber: true"
      validate={(newVal) => /^[0-9]*$/.test(val)}
    />
  );
};

Focus

By default, the first input is auto focused when component mounted, and we can give the onFocus, onBlur method to sync focus state.

disable auto focus by autoFocus prop.

import { useState } from 'react';
import AuthCode from 'react-auth-code';

const App = () => {
  const [isFocused, setIsFocused] = useState(false);

  return (
    <AuthCode
      autoFocus={true}
      onFocus={() => setIsFocused(true)}
      onBlur={() => setIsFocused(true)}
    />
  );
};

Custom Input

By default, each input is wrapped with a label, we can change the wrapper with renderInput prop, and inputClassName to customize our input style.

const App = () => {
  // ...
  return (
    <AuthCode
      inputClassName="w-5 text-4xl text-center p-0 pb-2"
      renderInput={(input, i) => (
        <label key={i} className="px-5">
          {input}
        </label>
      )}
    />
  );
};

Loop

After entering all codes, the last input will be focused and new input code will by default, replace current field code.

If loop is set to true, the new input code will be auto moved to the first field, and the second field will be focused then. User would not have to manually touch the first field to input codes again.

loop feature only take effect when fields > 1.

const App = () => {
  // ...
  return (
    <AuthCode loop={true} />
  );
};

Programming Reference

By passing a reference to <AuthCode>, we can call some useful methods like below.

import { useRef } from 'react';
import AuthCode, { AuthCodeRef } from 'react-auth-code';

const App = () => {
  const authCodeRef = useRef<AuthCodeRef>(null);

  const clearCodes = () => {
    authCodeRef.current?.clear();
  };

  return (
    <AuthCode ref={authCodeRef} />
  );
};

available methods

MethodDescription
clear(): voidclear all input values
focus(index: Number = 0): voidfocus input with given index
getInput(index: Number = 0): InputDetailget input detail with given index
getCodes(): String[]get codes in inputs
getValue(): Stringget joined code string
setCodes: Dispatch<SetStateAction<string[]>>react setState function of codes
setCode(index: Number, value: String): voidset code value with index
interface InputDetail {
  value: HTMLInputElement | null
  next: HTMLInputElement | null
  prev: HTMLInputElement | null
}

Props

PropTypeDescriptionDefault ValueObservations
autoFocusBooleanauto focus first input on mounttrue
autoCompleteBooleanenable auto complete with one-time-code in first inputfalse
autoReplaceBooleanwhether replace value for input already had value with last charactertrue
ariaLabelStringAccessibility
renderInput(input: JSX.Element, index: Number) => JSX.Elementrender function for each field item(input, i) => <label key={i}>{input}</label>
disabledBooleanwhether disable all inputsfalse
fieldsNumbernumber of inputs6
inputTypeStringinput typetel
inputClassNameStringinput className
loopBooleanwhether auto focus to second input when input exceed fields lengthfalse
onlyNumberBooleanonly allow 0-9 numbertrue
onFocus(e: ReactEvent, index: Number) => voidtrigger when input focused() => {}
onBlur(e: ReactEvent, index: Number) => voidtrigger when input blured() => {}
onChange(codes: String[]) => voidtrigger when any value changed() => {}
onComplete(codes: String[]) => voidtrigger when codes length reach fields number() => {}
placeholderStringinput placeholder
validate(value: String) => Booleancustom validate function for input value() => true

License

Licensed under the MIT License, Copyright © 2023-present Johnny Wang johnnywang1994.

1.0.4

11 months ago

1.0.3

12 months ago

1.0.2

12 months ago

1.0.1

12 months ago

1.0.0

12 months ago