I was trying to develop a typical form, but I faced a problem with displaying the phone number above the mask. When I enter a phone number into appropriate input, it displays no actual data.
For example: when I enter 1,2,3, it displays: ++ ++ 7 1. When I press the Backspace button it adds characters instead of removing them.
My function, which takes in numbers (joined together phone number) and returns formatted numbers, works well. I don't know why this problem happened and how to solve it. Probably, the problem is not with phoneNumberMask function, but with the surrounded code.
Please, help me to understand, what is the matter and how to solve it.
gitHub:https://github.com/AlexKor-5/FormChallenge/commit/011b79d2009fea70b028e5335e67e73988a46124
Thanks in advance!
src/components/PhoneNumberInput/PhoneNumberInput.js
import React, { useState } from 'react'
import { TextField } from 'formik-mui'
import { Field } from 'formik'
import phoneNumberMask from '../../services/phoneNumberMask/phoneNumberMask'
console.log(
phoneNumberMask({
mask: '+x xxx xxx xx xx',
phone: '78905556781',
visible: false,
})
)
export const PhoneNumberInput = ({ text, name }) => {
const [click, setClick] = useState(true)
const [entered, setEntered] = useState('')
const handleChange = event => {
// setEntered(event.target.value)
setEntered(
phoneNumberMask({
mask: '+x xxx xxx xx xx',
phone: event.target.value,
visible: false,
})
)
}
const handleClick = () => {
click && setEntered('+7')
setClick(false)
}
return (
<Field
component={TextField}
label={text}
value={entered}
name={name}
variant="outlined"
fullWidth
onChange={handleChange}
onClick={handleClick}
/>
)
}
const phoneNumberMask = obj => {
let i = -1
let resMask = ''
const change = (mask, phoneNumber) => {
if (i > phoneNumber.length) return
i++
resMask = mask.toLowerCase().replace(/x/i, phoneNumber[i] || 'x')
change(resMask, phoneNumber)
}
change(obj.mask, obj.phone)
return obj.visible
? resMask
: resMask
.split('')
.filter(s => s !== 'x')
.join('')
}
export default phoneNumberMask