Formatting dates and numbers in React

Formatting numbers and dates is a common requirement for lots of apps but how do we do this in react apps?

Let’s say we have a component in our app that shows a list of customers, looking like this:

… and here’s the current code for this component:

… with the following data:

You can see that we need to clean up the revenue and first sale data by formatting them.

Formatting numbers

We can use Intl.NumberFormat to format the revenue:

In the above example we are formatting to revenue using Great British locale, using the Great British currency style.

So, we now have this:

But what if we don’t want the decimals in the revenue? We just add the min and max fraction digits in the options:

Formatting dates

We could just use toLocaleDateString instead of toString:

… which gives us a nice short date:

However, we can use Intl.DateTimeFormat to gain more control on the formatting:

Here we are specifying a 2 digit day, a long month and a 4 digit year.

So, here’s our final CustomerSearchResults component code:

… and here’s what it looks like:

Much better!

Recommended reading for building great React apps: