Unform

React Input Mask

React Input Mask

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 remove all type definitions from the 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
10export default function InputMask({ name, ...rest }: Props) {
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};
Edit this page on GitHub

On this page