DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 15

The task is to implement a PhoneNumberInput component that

  1. accepts only numerical digits
  2. formats the number automatically as (123)456-7890 by
  3. adding the parentheses when the 4th digit is added
  4. 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>
// }

Enter fullscreen mode Exit fullscreen mode

First, the input value is declared in a state variable

const[value,setValue] = useState("")
Enter fullscreen mode Exit fullscreen mode

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, "")

Enter fullscreen mode Exit fullscreen mode

Next, the input should not accept more than 10 digits

if(digits.length > 10) {
digits = digits.slice(0,10)
}
Enter fullscreen mode Exit fullscreen mode

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)}`
     }
Enter fullscreen mode Exit fullscreen mode

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>
    )
}

Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)