How to Easily Format Phone Numbers in React with PatternFormat

Semih Celik
1 min readSep 7, 2024

--

In modern web applications, user experience is key, and a well-formatted phone number input can make a big difference. PatternFormat allows you to easily format phone numbers while maintaining simplicity and control. In this article, we’ll explore how to implement a phone number input using PatternFormat in React, with clean, readable code and a smooth user experience.

To get started, install the react-number-format package that includes the PatternFormat component:

npm i react-number-format

Now, let’s use PatternFormat to create a phone number input field in React. This component automatically formats the phone number as the user types.

import { PatternFormat } from 'react-number-format';
import React, { useState } from 'react';

const PhoneNumberInput = () => {
const [phoneNumber, setPNumber] = useState('');

return (
<PatternFormat
format="### ### ## ##"
mask=" "
type="tel"
onChange={(e) => setPNumber(e.target.value)}
/>
);
};

export default PhoneNumberInput;

Thank you for reading! I hope this guide helps you implement phone number formatting effortlessly in your React projects. Feel free to share your thoughts or questions in the comments below.

--

--

Semih Celik
Semih Celik

Written by Semih Celik

I am looking for Frontend Developer positions. You can reach out to me on LinkedIn for communication and to view my CV. https://www.linkedin.com/in/msemihcelik

No responses yet