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';45function Input({ name, onChangeText, rawValue, ...rest }) {6 // add handleOnChange7 const handleOnChange = useCallback(8 text => {9 if (inputRef.current) inputRef.current.value = text;1011 if (onChangeText) onChangeText(text);12 },13 [onChangeText],14 );1516 useEffect(() => {17 registerField({18 // modify getValue19 getValue(ref) {20 return rawValue || ref.value;21 },22 });23 }, [fieldName, rawValue, registerField]);2425 return (26 <TextInput27 ref={inputRef}28 defaultValue={defaultValue}29 onChangeText={handleOnChange}30 {...rest}31 />32 );33}3435export 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';34import Input from '../Input';56const InputMask = ({ type, ...rest }) => {7 const [value, setValue] = useState('');8 const [rawValue, setRawValue] = useState('');910 const handleOnChangeText = useCallback((maskedValue, unmaskedValue) => {11 setValue(maskedValue);12 setRawValue(unmaskedValue);13 }, []);1415 return (16 <TextInputMask17 type={type}18 includeRawValueInChangeText19 value={value}20 onChangeText={handleOnChangeText}21 customTextInput={Input}22 customTextInputProps={{23 rawValue,24 ...rest,25 }}26 {...rest}27 />28 );29};3031export default 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" />16 <InputMask type="cpf" name="cpf" keyboardType="numeric" />17 <Button18 onPress={() => formRef.current.submitForm()}19 title="console.log"20 />21 </Form>22 </View>23 );24};