The task is to implement a PhoneNumberInput component that
- accepts only numerical digits
- formats the number automatically as (123)456-7890 by
- adding the parentheses when the 4th digit is added
- also adding - before the 7th digit The boilerplate code:
import React from 'react'
export function PhoneNumberInput() {
// your code here
return <input data-testid="phone-number-input"/>
}
// if you want to try your code on the right panel
// remember to export App() component like below
// export function App() {
// return <div>your app</div>
// }
First, the input value is declared in a state variable
const[value,setValue] = useState("")
Next, a function is created to handle changes to the input field. Inside the function, a regex is applied to ensure that the input accepts only numbers, no spaces, letters or symbols
let digits = e.target.value.replace(/\D/g, "")
Next, the input should not accept more than 10 digits
if(digits.length > 10) {
digits = digits.slice(0,10)
}
Finally, the input should be formatted automatically as the input is being filled.
let formatted = digits;
if(digits.length > 3 && digits.length <= 6) {
formatted = `(${digits.slice(0,3)})${digits.slice(3)}`
} else if(digits.length > 6) {
formatted = `(${digits.slice(0,3)})${digits.slice(3,6)}-${digits.slice(6)}`
}
The complete code looks like this
import React, { useState } from 'react'
export function PhoneNumberInput() {
// your code here
const[value, setValue] = useState("")
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
let digits = e.target.value.replace(/\D/g, "")
if(digits.length > 10) {
digits = digits.slice(0,10);
}
let formatted = digits;
if(digits.length > 3 && digits.length <= 6) {
formatted = `(${digits.slice(0,3)})${digits.slice(3)}`
} else if(digits.length > 6) {
formatted = `(${digits.slice(0,3)})${digits.slice(3,6)}-${digits.slice(6)}`
}
setValue(formatted)
}
return <input value={value} onChange={handleChange} data-testid="phone-number-input"/>
}
// if you want to try your code on the right panel
// remember to export App() component like below
export function App() {
return (
<div>
<PhoneNumberInput />
</div>
)
}
That's all folks!
Top comments (0)