Unform

React Native Input Mask

React Native Input Mask

React Native Masked Text offers an easy way to add masks to inputs.

Input component

Create a base Input component, as described in the React Native example.

Here is a small difference: assuming that the data to be sent in the form should not be formatted, we will use a rawText property that will inform us of the component's gross value.

Note that getValue can return the rawText property, that is, if the form does not use an InputMask, the returned value will be the one stored in inputRef

1import React, { useRef, useEffect, useCallback } from 'react';
2import { TextInput } from 'react-native';
3import { useField } from '@unform/core';
4
5function Input({ name, label, onChangeText, rawText, onInitialData, ...rest }) {
6 // this will cause the InputMask to be updated if the Form receives initial data
7 useEffect(() => {
8 if (onInitialData) onInitialData(defaultValue);
9 }, [defaultValue, onInitialData]);
10
11 useEffect(() => {
12 registerField({
13 // modify getValue
14 getValue() {
15 if (rawText) return rawText;
16
17 if (inputRef.current) return inputRef.current.value;
18
19 return '';
20 },
21 });
22 }, [fieldName, rawText, registerField]);
23
24 return (
25 {...}
26 );
27}
28
29export default Input;

InputMask component

Inform which component should be rendered using the customTextInput property, in this case Input. Add rawText to the Input properties using customTextInputProps

1import React, { useState, useCallback, forwardRef } from 'react';
2import { TextInputMask } from 'react-native-masked-text';
3
4import Input from '../Input';
5
6const InputMask = ({ type, ...rest }, inputRef) => {
7 const [text, setText] = useState('');
8 const [rawText, setRawText] = useState('');
9
10 const handleChangeText = useCallback((maskedText, unmaskedText) => {
11 setText(maskedText);
12 setRawText(unmaskedText);
13 }, []);
14
15 return (
16 <TextInputMask
17 type={type}
18 includeRawValueInChangeText
19 value={text}
20 onChangeText={handleChangeText}
21 customTextInput={Input}
22 customTextInputProps={{
23 ref: inputRef,
24 rawText,
25 onInitialData: setText,
26 }}
27 {...rest}
28 />
29 );
30};
31
32export default forwardRef(InputMask);

Example

1const App = () => {
2 const formRef = useRef(null);
3
4 function handleSubmit(data) {
5 /**
6 Out: { first_name: 'Lorem Ipsum', cpf: '11111111111' }
7 On screen: { first_name: 'Lorem Ipsum', cpf: '111.111.111-11' }
8 */
9 console.log(data);
10 }
11
12 return (
13 <View style={{ flex: 1, justifyContent: 'center', alignContent: 'center' }}>
14 <Form ref={formRef} onSubmit={handleSubmit}>
15 <Input name="first_name" label="Name" />
16 <InputMask type="cpf" name="cpf" keyboardType="numeric" label="CPF" />
17 <Button
18 onPress={() => formRef.current.submitForm()}
19 title="console.log"
20 />
21 </Form>
22 </View>
23 );
24};
Edit this page on GitHub