Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Format Numbers with Separators and Currency Symbols using react-intl FormattedNumber

    Damon BauerDamon Bauer
    15 - 16.8.4

    Using a react-intl FormattedNumber component, we'll pass a Number and a few additional props in order to render the correct separator and currency symbols for different languages.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    We'll start by importing FormattedNumber from react-intl. We'll be formatting the prices of the book, ensuring that value separators and currency symbols are added in the appropriate places.

    First, let's take a look at some changes I've made to the mock data that's populating each book detail view. Instead of a single price, I've changed the price value to be an object with keys that correspond to the different languages that our app supports.

    The value of each is the price in their respective country. I'm going to get the same function to grab the user's locale as in our index file. We'll set that in our component. I'll just get rid of this merchant price text that we have set right now, and I'll replace that with a formatted number.

    Into the value prop, I'll add merchant.price. Since merchant.price is now an object, we need to look up the locale, so I'll provide the bracket notation and pass locale to it; locale here, in the bracket notation, will correspond to the locale that we're grabbing off the navigator object and will find the locale that corresponds to the price object in our book data file.

    Next, let's pass a prop of style. We'll give it a value of currency. We'll pass a currency display prop with a value of symbol to display the correct currency symbol. Finally, we need a currency prop, and this will tell react-intl which currency to display the price in.

    Since we want that dynamic display of the currency, we need to add a ternary operator, so I'll say locale triple equals the string of EN-US. If that's true, we want to return the currency of USD.

    Otherwise, we want to return the currency of EUR. If you had more locales or currencies to support, you could provide this prop a function that returns the correct currency, instead of just a ternary operator.

    That's it. You can see each language is now displaying the correct price and currency symbols.