Skip to content

Instantly share code, notes, and snippets.

@lucasfloriani
Created April 1, 2020 18:39
Show Gist options
  • Select an option

  • Save lucasfloriani/933eb0fada9e3ecbfa0fe220e05fb5a1 to your computer and use it in GitHub Desktop.

Select an option

Save lucasfloriani/933eb0fada9e3ecbfa0fe220e05fb5a1 to your computer and use it in GitHub Desktop.
Component with mask that accepts phone and mobile phone values
/* 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