react-tiny-mask
TypeScript icon, indicating that this package has built-in type declarations

0.0.3 • Public • Published

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

Name Required Type Default Description
mask true string, Array<string> Mask pattern
tokens false Object { '#': { pattern: /\d/ } } Custom tokens for mask
component false ElementType Custom 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} />;
};

Package Sidebar

Install

npm i react-tiny-mask

Weekly Downloads

11

Version

0.0.3

License

MIT

Unpacked Size

9.37 kB

Total Files

16

Last publish

Collaborators

  • yanykin