How to Format Phone Numbers in React

Shubham Vora Feb 02, 2024
  1. Create the Custom Logic to Format the Phone Number
  2. Use the react-phone-number-input Library to Format the Phone Number According to the Country
How to Format Phone Numbers in React

In this article, we will learn to format phone numbers in React. Developers often face the problem of formatting the input value while developing React applications.

Here, we will format a 10-digit phone number in the (###) ### - #### format. To achieve our goal, we have created the custom logic in the first example and used the React built-in library in the second example.

Create the Custom Logic to Format the Phone Number

We can create custom logic to format the phone numbers according to our requirements. Users can follow the below steps to format the phone numbers.

  • If the input is empty, return the empty string or value.
    if (!input) return input;
    
  • Filter the numbers from the input and remove other characters.
    const numberInput = input.replace(/[^\d]/g, "");
    
  • Take the length of the phone number input value.
    const numberInputLength = numberInput.length;
    
  • If the input length is less than 4, return the phone number as it is.
    if (numberInputLength < 4) {
    	return numberInput;
    }
    
  • If the length of the input value is between 4 and 7, format it like (###) #__.
     if (numberInputLength < 7) {
    	return `(${numberInput.slice(0, 3)}) ${numberInput.slice(3)}`;
    }
    
  • And if the length of the input value is more than 10, format it like (###) ### - #___.
    if{
    	return `(${numberInput.slice(0, 3)}) ${numberInput.slice(3,6)}-${numberInput.slice(6, 10)}`;
    }
    

In the example code below, we have created the <input> to take the phone number input. Whenever the value of the input changes, it will call the handlephoneNumber() function.

The handlephoneNumber() function calls the formatPhoneNumber() function to format the phone number according to the above steps. After formatting the phone number, the handlephoneNumber() function sets the formatted value of the phone number into the input.

Example Code:

// import react and usestate
import React, { useState } from "react";

function formatPhoneNumber(input) {
  //  if the input is null, return a null value
  if (!input) return input;
  // remove all characters from the input except number input.
  const numberInput = input.replace(/[^\d]/g, "");
  //  take the length of the value of the input
  const numberInputLength = numberInput.length;
  // if the number length is 1, 2, or 3, then return it as it is.
  if (numberInputLength < 4) {
    return numberInput;
  } else if (numberInputLength < 7) {
    // if the number input length is 4, 5, or 6, format it accordingly.
    return `(${numberInput.slice(0, 3)}) ${numberInput.slice(3)}`;
  } else {
    //  if the number input length is 7, 8, 9, 10, or more, format it like the below.
    return `(${numberInput.slice(0, 3)}) ${numberInput.slice(
      3,
      6
    )}-${numberInput.slice(6, 10)}`;
  }
  // return empty string in case any condition doesn't satisfy.
  return "";
}

export default function App() {
  // Binded phoneNumber with an input value and setPhoneNUmber is used to make changes to the value of phoneNumber
  const [phoneNumber, setphoneNumber] = useState("");
  //  whenever input will change, handlephoneNumber() function will invoke.
  const handlephoneNumber = (e) => {
    // format phone number
    const formattedPhoneNumber = formatPhoneNumber(e.target.value);
    //  set the formatted phone number to the input value
    setphoneNumber(formattedPhoneNumber);
  };

  return (
    <div style={{ textAlign: "center", marginTop: "30px" }}>
      {/* number input to take phone numbetr */}
      <input onChange={(e) => handlephoneNumber(e)} value={phoneNumber} />
    </div>
  );
}

Output:

format phone number - one

In the above output, users can see formatted phone numbers according to the length of the input value. Also, it is not allowing users to add any other character to the input except numbers.

Furthermore, users can’t enter a number with more than a length of 10.

Use the react-phone-number-input Library to Format the Phone Number According to the Country

The react-phone-number-input library of React allows us to format the phone number according to different countries. We can import the library in our code and use the <phoneInput> component to take the phone number input, which automatically formats the phone number.

Before we look at the example, users must install the library in the React app. For that, open the terminal in the same directory where your React app is and enter the command:

npm install react-phone-number-input

Now, users need to use the <phoneInput> component in the app like below. Here, the phoneNumber variable keeps track of the input’s value, and the setPhoneNumber() function sets the value to the phoneNumber when the user changes the input value.

<PhoneInput value={phoneNumber}  onChange={setphoneNumber}/>

We have implemented the formatting of phone numbers with a single line of code. Users can see the full working code below.

Example Code:

//  import required libraries
import 'react-phone-number-input/style.css'
import PhoneInput from 'react-phone-number-input';
import { useState } from 'react';

function App() {
  const [phoneNumber, setphoneNumber] = useState()
  // using phoneInput component of react-phone-number-input library
  return (
    <PhoneInput
      placeholder="Add Your Phone Number Here"
      value={phoneNumber}
      onChange={setphoneNumber}/>
  )
}

export default App;

Output:

format phone number - two

In the above output, users can see that it formats the phone number according to the country they select from the dropdown. Also, it auto-selects the country according to the length of the phone number.

The second method is simpler in writing code but doesn’t stop users from entering numbers. Users can enter phone numbers of any length, which is not good practice while developing the application.

We can customize the phone numbers according to our requirements by writing custom logic as we have written in the first method. So, it is recommended that programmers use custom logic.

Author: Shubham Vora
Shubham Vora avatar Shubham Vora avatar

Shubham is a software developer interested in learning and writing about various technologies. He loves to help people by sharing vast knowledge about modern technologies via different platforms such as the DelftStack.com website.

LinkedIn GitHub