0.0.3 • Published 6 months ago

react-tiny-mask v0.0.3

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

react-tiny-mask

Lightweight (<2KB gzipped) and dependency free mask input, created specifically for React (inspired by vue-the-mask)

Installation

yarn add react-tiny-mask

or

npm i react-tiny-mask

Usage

import { InputMask } from 'react-tiny-mask';

export const App = () => {
  return <InputMask mask="+7 ### ###-##-##" />;
};

Properties

NameRequiredTypeDefaultDescription
masktruestring, Array<string>Mask pattern
tokensfalseObject{ '#': { pattern: /\d/ } }Custom tokens for mask
componentfalseElementTypeCustom component instead of regular <input />

mask

Mask pattern. Can be a string or an array of strings (dynamic mask).

<InputMask mask="+7 ### ###-##-##" />

or

<InputMask mask={['###-#', '####-#', '#####-#', '######-#']} />

tokens

By default, one token is defined:

{ '#': { pattern: /\d/ } } // digits

For more complex masks, you can define your own tokens.

For example, Colors HEX:

import { InputMask } from 'react-tiny-mask';

const tokens = {
  '#': {
    pattern: /[0-9a-fA-F]/,
  },
};

export const App = () => {
  return <InputMask mask="######" tokens={tokens} />;
};

For custom tokens you can define transform function, applied to a character before masking. For example, transforming letters to uppercase on input:

import { InputMask } from 'react-tiny-mask';

const tokens = {
  '#': {
    pattern: /[0-9a-fA-F]/,
    transform: (value: string) => value.toUpperCase(),
  },
};

export const App = () => {
  return <InputMask mask="######" tokens={tokens} />;
};

component

Property for integration with other input components:

import { InputMask } from 'react-tiny-mask';

const CustomInput = (props) => <input {...props} style={{ color: 'red' }} />;

export const App = () => {
  return <InputMask mask="+7 ### ###-##-##" component={CustomInput} />;
};

Dynamic mask

Pass mask as array of strings to make it dynamic. The suitable mask will be chosen by length (smallest first):

import { InputMask } from 'react-tiny-mask';

const mask = ['###-#', '####-#', '#####-#', '######-#'];

export const App = () => {
  return <InputMask mask={mask} />;
};
0.0.3

6 months ago

0.0.2

8 months ago

0.0.1

8 months ago