Created
January 14, 2020 13:32
-
-
Save ErikGMatos/ed0940418e1f3dbfce06d78d0b050e71 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useRef, useEffect } from 'react'; | |
| import MaskedInput from 'react-text-mask'; | |
| import { useField, Input } from '@rocketseat/unform'; | |
| import PropTypes from 'prop-types'; | |
| export default function InputMaskComponent({ name, mask, ...rest }) { | |
| const { fieldName, defaultValue, registerField, error } = useField(name); | |
| const ref = useRef(); | |
| function unmask(value) { | |
| let unmasked = value | |
| .replace(/\.+/g, '') | |
| .replace(/-/g, '') | |
| .replace(/\//g, '') | |
| .replace(/\(/g, '') | |
| .replace(/\)/g, '') | |
| .replace(/ /g, ''); | |
| if (name === 'whatsapp') { | |
| unmasked = unmasked.replace('+55', ''); | |
| } | |
| return unmasked; | |
| } | |
| function parseValue({ textMaskInputElement }) { | |
| const value = unmask(textMaskInputElement.state.previousConformedValue); | |
| return value; | |
| } | |
| useEffect(() => { | |
| if (ref.current) { | |
| registerField({ | |
| name, | |
| ref: ref.current, | |
| path: '', | |
| parseValue, | |
| }); | |
| } | |
| }, [ref]); // eslint-disable-line | |
| return mask ? ( | |
| <> | |
| <MaskedInput | |
| ref={ref} | |
| name={fieldName} | |
| id={fieldName} | |
| defaultValue={defaultValue} | |
| mask={mask} | |
| guide={false} | |
| {...rest} | |
| /> | |
| {error && <span>{error}</span>} | |
| </> | |
| ) : ( | |
| <Input name={fieldName} {...rest} /> | |
| ); | |
| } | |
| InputMaskComponent.defaultProps = { | |
| mask: null, | |
| error: null, | |
| }; | |
| InputMaskComponent.propTypes = { | |
| name: PropTypes.string.isRequired, | |
| mask: PropTypes.oneOfType([ | |
| PropTypes.string, | |
| PropTypes.arrayOf( | |
| PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.any]) | |
| ), | |
| ]), | |
| error: PropTypes.string, | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment