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 rawValue property that will inform us of the component's gross value.

Note that getValue can return the rawValue 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, onChangeText, rawValue, ...rest }) {
6 // add handleOnChange
7 const handleOnChange = useCallback(
8 text => {
9 if (inputRef.current) inputRef.current.value = text;
10
11 if (onChangeText) onChangeText(text);
12 },
13 [onChangeText],
14 );
15
16 useEffect(() => {
17 registerField({
18 // modify getValue
19 getValue(ref) {
20 return rawValue || ref.value;
21 },
22 });
23 }, [fieldName, rawValue, registerField]);
24
25 return (
26 <TextInput
27 ref={inputRef}
28 defaultValue={defaultValue}
29 onChangeText={handleOnChange}
30 {...rest}
31 />
32 );
33}
34
35export default Input;

InputMask component

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

1import React, { useState, useCallback } from 'react';
2import { TextInputMask } from 'react-native-masked-text';
3
4import Input from '../Input';
5
6const InputMask = ({ type, ...rest }) => {
7 const [value, setValue] = useState('');
8 const [rawValue, setRawValue] = useState('');
9
10 const handleOnChangeText = useCallback((maskedValue, unmaskedValue) => {
11 setValue(maskedValue);
12 setRawValue(unmaskedValue);
13 }, []);
14
15 return (
16 <TextInputMask
17 type={type}
18 includeRawValueInChangeText
19 value={value}
20 onChangeText={handleOnChangeText}
21 customTextInput={Input}
22 customTextInputProps={{
23 rawValue,
24 ...rest,
25 }}
26 {...rest}
27 />
28 );
29};
30
31export default 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" />
16 <InputMask type="cpf" name="cpf" keyboardType="numeric" />
17 <Button
18 onPress={() => formRef.current.submitForm()}
19 title="console.log"
20 />
21 </Form>
22 </View>
23 );
24};
Edit this page on GitHub