Created
April 1, 2020 18:39
-
-
Save lucasfloriani/933eb0fada9e3ecbfa0fe220e05fb5a1 to your computer and use it in GitHub Desktop.
Component with mask that accepts phone and mobile phone values
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
| /* Form need to be wrapped in FormikProvider to access formik context */ | |
| import React from 'react' | |
| import PropTypes from 'prop-types' | |
| import { useFormikContext } from 'formik' | |
| import TextField from '@atoms/TextField' | |
| const PhoneInput = ({ ...props }) => { | |
| const { setFieldValue } = useFormikContext() | |
| const { name, value } = props | |
| return ( | |
| <TextField | |
| {...props} | |
| maskType={value.replace(/_+/g, '').length <= 14 ? 'PHONE' : 'MOBILE_PHONE'} | |
| onChange={({ target }) => { | |
| const phoneWithoutMaskPlaceholder = target.value.replace(/[^0-9()-\s]+/g, '') | |
| const tracoIndex = phoneWithoutMaskPlaceholder.length <= 14 ? 9 : 10 | |
| const formatedPhone = phoneWithoutMaskPlaceholder | |
| .split('-') | |
| .join('') | |
| .split('') | |
| .map((letter, index) => index === tracoIndex ? `-${letter}` : letter) | |
| .join('') | |
| setFieldValue(name, formatedPhone) | |
| }} | |
| /> | |
| ) | |
| } | |
| PhoneInput.propTypes = { | |
| name: PropTypes.string.isRequired, | |
| value: PropTypes.string.isRequired, | |
| } | |
| export default PhoneInput |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment