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';45function Input({ name, label, onChangeText, rawText, onInitialData, ...rest }) {6 // this will cause the InputMask to be updated if the Form receives initial data7 useEffect(() => {8 if (onInitialData) onInitialData(defaultValue);9 }, [defaultValue, onInitialData]);1011 useEffect(() => {12 registerField({13 // modify getValue14 getValue() {15 if (rawText) return rawText;1617 if (inputRef.current) return inputRef.current.value;1819 return '';20 },21 });22 }, [fieldName, rawText, registerField]);2324 return (25 {...}26 );27}2829export 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';34import Input from '../Input';56const InputMask = ({ type, ...rest }, inputRef) => {7 const [text, setText] = useState('');8 const [rawText, setRawText] = useState('');910 const handleChangeText = useCallback((maskedText, unmaskedText) => {11 setText(maskedText);12 setRawText(unmaskedText);13 }, []);1415 return (16 <TextInputMask17 type={type}18 includeRawValueInChangeText19 value={text}20 onChangeText={handleChangeText}21 customTextInput={Input}22 customTextInputProps={{23 ref: inputRef,24 rawText,25 onInitialData: setText,26 }}27 {...rest}28 />29 );30};3132export default forwardRef(InputMask);
Example
1const App = () => {2 const formRef = useRef(null);34 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 }1112 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 <Button18 onPress={() => formRef.current.submitForm()}19 title="console.log"20 />21 </Form>22 </View>23 );24};