Formatting Dates, Numbers, and Lists with React-Intl

Image for post
Image for post
Photo by Amy Simpson on Unsplash

Many apps have to be made usable by different users from various parts of the world.

To make this easier, we can use the react-intl to do the internationalization for us.

In this article, we’ll look at how to get started with formatting dates with the react-intl library.

FormattedRelativeTime

We can use the FormattedRelativeTime component to format relative time.

For example, we can write:

We use the FormattedRelativeTime component with a few props.

value has the relative time value in seconds.

numeric meabns whether we display the item numerically.

updateIntervalInSeconds is the time interval in seconds in which we update the formatted string.

Number Formatting Components

We can format numbers with a few components.

They include the FormattedNumber , FormattedNumberParts and FormattedPlural components.

FormattedNumber

The FormattedNumber complete renders the formatted number into a fragment.

We can customize this as we wish.

For instance, we can use it by writing:

We use the FormattedNumber component with the value to format.

style is set to unit so that we format it with the unit.

unit is the unit we want to have with the number.

unitDisplay is the style of the unit we display.

We can only pass in units that are allowed by the Inyl.NumberFormat constructor.

narrow means that we display the abbreviation.

So we get:

as a result.

FormattedNumberParts

The FormattedNumberParts component lets us format each part of the number string individually.

For instance, we can write:

to format each part of the number.

In our example, the first parts entry is the thousands digit.

The 2nd part is the comma thousand separator.

The 3rd is the remaining digits.

FormattedPlural

We can format plural numbers with the FormattedPlural component.

To use it, we can write:

We use the FormattedPlural compoennt to render the singular or plural according to the value that’s passed into the value prop.

List Formatting Components

We can format lists with react-intl.

FormattedList

We can use the FormmatedList component to format lists the way we want.

For instance, we can write:

to combine the array in the value prop into a string.

We specified that the type of conjunction so that we combine it with ‘and’ or their equivalent on other languages.

Since we set the locale to English, we get:

Conclusion

We can format relative time, lists, and numbers with react-intl.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store