Unform

React Input Mask

Table of Contents

React Input Mask offers an easy way to add masks to inputs.

⚠️ All examples below are using TypeScript, if you're not using it you can simply remove all type definitions as the React.FC<Props> from component definition.

Example

1import React, { useRef, useEffect } from 'react';
2import ReactInputMask, { Props as InputProps } from 'react-input-mask';
3
4import { useField } from '@unform/core';
5
6interface Props extends InputProps {
7 name: string;
8}
9
10const InputMask: React.FC<Props> = ({ name, ...rest }) => {
11 const inputRef = useRef(null);
12 const { fieldName, registerField, defaultValue, error } = useField(name);
13
14 useEffect(() => {
15 registerField({
16 name: fieldName,
17 ref: inputRef.current,
18 path: 'value',
19 setValue(ref: any, value: string) {
20 ref.setInputValue(value);
21 },
22 clearValue(ref: any) {
23 ref.setInputValue('');
24 },
25 });
26 }, [fieldName, registerField]);
27
28 return (
29 <ReactInputMask ref={inputRef} defaultValue={defaultValue} {...rest} />
30 );
31};
32
33export default InputMask;
Edit this page on GitHub