Lightweight (<2KB gzipped) and dependency free mask input, created specifically for React (inspired by vue-the-mask)
yarn add react-tiny-mask
or
npm i react-tiny-mask
import { InputMask } from 'react-tiny-mask';
export const App = () => {
return <InputMask mask="+7 ### ###-##-##" />;
};
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 pattern. Can be a string or an array of strings (dynamic mask
).
<InputMask mask="+7 ### ###-##-##" />
or
<InputMask mask={['###-#', '####-#', '#####-#', '######-#']} />
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} />;
};
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} />;
};
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} />;
};