react-native-document-mask
Version:
Document Mask for React Native on iOS and Android.
143 lines (119 loc) • 3.49 kB
JavaScript
import React, { Component } from "react";
import { View, Text } from "react-native";
import PropTypes from "prop-types";
import styles from "./styles";
import Aux from "./settings";
export default class MaskCpfCnpj extends Component{
constructor(props){
super(props)
this.state = {
formatted: null,
masker: "[000].[000].[000]-[00]"
}
}
componentDidMount() {
console.log('inpt', this.props.cpf);
}
setNativeProps(nativeProps) {
this.input.setNativeProps(nativeProps);
}
format(value) {
if (value.length < 15 && this.props.cpf) {
this.setState({ masker: "[000].[000].[000]-[000]" })
}
if (value.length > 14 && this.props.cnpj) {
this.setState({ masker: "[00].[000].[000]/[0000]-[00]" })
}
if(this.props.cnpj && !this.props.cpf){
this.setState({ masker: "[00].[000].[000]/[0000]-[00]" })
}
if(!this.props.cnpj && this.props.cpf){
this.setState({ masker: "[000].[000].[000]-[00]"})
}
if(!this.props.cpf && !this.props.cnpj){
this.setState({ masker: "[00000000000000000000000000000000000000000000000]" })
}
return value;
}
set(txt, txtOut) {
this.setState({ formatted: this.format(txt) })
this.props.setData && this.props.setData(txtOut);
}
focus() {
this.input.focus();
}
blur() {
this.input.blur();
}
clear() {
this.input.clear();
}
isFocused() {
return this.input.isFocused();
}
_renderInput(){
const {
submit,
keyboardTypeSubmit,
placeholder,
inputStyle,
placeholderTextColor,
autoFocus,
onFocus,
onEndEditing,
...otherProps
} = this.props;
return (
<Aux
onEndEditing={onEndEditing}
onFocus={onFocus}
autoFocus={autoFocus}
placeholder={placeholder}
placeholderTextColor={placeholderTextColor}
value={this.state.formatted}
onSubmitEditing={() =>
submit && submit()
}
ref={ref => {
this.input = ref;
}}
onChangeText={(formatted, extracted) => {
console.log(formatted); // +1 (123) 456-78-90
console.log(extracted); // 1234567890
this.set(formatted, extracted);
}}
mask={this.state.masker}
keyboardType={"numeric"}
returnKeyType={keyboardTypeSubmit}
style={[ styles.input, inputStyle ]}
{...otherProps}
/>
);
}
render(){
const { containerStyle } = this.props;
return (
<View style={[ styles.container, containerStyle]}>
{this._renderInput()}
</View>
);
}
};
MaskCpfCnpj.propTypes = {
...Text.propTypes,
cpf: PropTypes.bool,
cnpj: PropTypes.bool,
submit: PropTypes.func,
setData: PropTypes.func.isRequired,
keyboardTypeSubmit: PropTypes.oneOf(['next', 'done', 'send', 'none']),
placeholder: PropTypes.string,
inputStyle: PropTypes.any,
containerStyle: PropTypes.any,
placeholderTextColor: PropTypes.string,
autoFocus: PropTypes.func,
onFocus: PropTypes.func,
onEndEditing: PropTypes.func,
}
MaskCpfCnpj.defaultProps = {
placeholder: "Digite o número do documento"
}