Phone Number Formatting Made Easy!

April Escobar
5 min readApr 27, 2021

Introduction:

Hello there and welcome to my personal notes.

This week’s post was originally going to be Part 2: The R in CRUD from my StickyNote mini-project blog series. However, while I was working on a new project today, I finally decided to format a phone number through the React package, react-number-format (learn more). I unexpectedly went through a lot trying to implement this component and decided to write about it. You’ll see more when you get to the conclusion.

Anyway, the more I build websites, the more I realize how standard a “Contact Us” form page is. Nine out of ten times, it certainly includes a phone input.

On a different project, a colleague of mine took the time to create a function that manually formats a phone number. It goes something like this:

const formatPhoneNumber = (e) => {  let formattedNumber;  const { name, value } = e.target;  const { length } = value;  // Filter non numbers
const regex = () => value.replace(/[^0-9\.]+/g, "");
// Set area code with parenthesis around it
const areaCode = () => `(${regex().slice(0, 3)})`;

// Set formatting for first six digits
const firstSix = () => `${areaCode()} ${regex().slice(3, 6)}`;

// Dynamic trail as user types
const trailer = (start) => `${regex().slice(start,
regex().length)}`;
if (length < 3) {
// First 3 digits
formattedNumber = regex();
} else if (length === 4) {
// After area code
formattedNumber = `${areaCode()} ${trailer(3)}`;
} else if (length === 5) {
// When deleting digits inside parenthesis
formattedNumber = `${areaCode().replace(")", "")}`;
} else if (length > 5 && length < 9) {
// Before dash
formattedNumber = `${areaCode()} ${trailer(3)}`;
} else if (length >= 10) {
// After dash
formattedNumber = `${firstSix()}-${trailer(6)}`;
}
const formattedObject = {
target: { name: name, value: formattedNumber }
};
handleChange(formattedObject);};

While I dearly commend them for their logic and hard work, it just seemed like a lot of code…I still utilized this code for other projects though. I admired their hard work and why reinvent the wheel when I can copy and paste.

Then, on another task with the same project, I was asked to format a string value to an accounting number, the standard ‘$8,888.88’. Now I could’ve followed my colleague’s lead and created a function that manually formatted the values but…I’m lazy. So I decided to look for a React package instead.

That’s when I discovered react-number-format.

Side note: This is the React component I used to format the string value to an accounting number.

const price = '8888.88'<NumberFormat 
value={parseFloat(price)}
displayType={'text'}
thousandSeparator={true}
prefix={'$'}
decimalScale={2}
/>

Phone Number Formatting Made Easy!

const [phone, setPhone] = useState('');<NumberFormat 
type="tel"
format="+1 (###) ###-####"
mask="_"
onValueChange={value => setPhone(value.formattedValue)}
required
/>
<p>Phone: {phone}</p>

Yup. That’s all I needed to get this:

While it’s nice to copy and paste, it’s also nice to understand the breakdown of the component.

Notice: The prop “onChange” is replaced by “onValueChange”. This actually returns the following object:

You can pick and choose which one you’d like. Although when rendering the value to the DOM for formatting purposes… You’d probably want to select the already formatted number, formattedValue.

Conclusion:

Anyway, I decided to create this blog post to help me in the future as again, these are my personal notes. I struggled accessing those values in the object earlier today but then recreating it to its own mini-project, I don’t know how or why, I got it all in one shot 😐…

Just to give you a better understanding, here’s what I went through today:

  1. Immediately used onChange because force of habit and failed. onChange didn’t invoke my handler function.
  2. Read the documentation to better understand the component and the many props it contains.
  3. Switched over to onValueChange and invoked my hander function and was able to print the value object on my console.
  4. Kept getting error messages about the use of React Hooks whenever I tried to set the state variable to the component’s value (might be another story to tell).
  5. Googled the error messages.
  6. Updated to the latest version of React.
  7. Read through the useState React documentation to see where things went wrong.
  8. Took a 15min break because I was a little butt hurt from this error message when I’ve used useState for over a year now.
  9. Couldn’t find the right answer I needed so I resorted to vanilla JavaScript and utilized document.getElementById(id);
  10. Really couldn’t access those keys in that value object… It’s weird because I used values.formattedValue and it kept giving me the whole object. I even used values.values.formattedValue and nope, still kept getting the whole object as my output.
  11. Tested, tested and tested like my life depended on it.
  12. Finally got what I needed.

Again, I don’t know what happened, but at the end of the day, yay for learning and better understanding it. In my attempt of recreating the problem, I ended up having a smooth experience instead!

Image Source

Let’s see how it goes when I update old projects with this package…

Thank you so much for reading this post. Please let me know if there’s any adjustments I need to make as I’m very open to feedback! Also, let me know if you went through a similar situation too. I’d love to lend you an ear :)

Cheers!

--

--