reactjsreact-intl

react-intl display currency symbol only


Working with react-intl and was looking to display a currency symbol only, after some text like USD$.

From what I have read so far in the documentation guessing FormattedNumber requires a default value.

Just wondering is it possible to display a currency symbol without a number value? such as $ (currently it returns NaN, due to missing number value)

Wondering has anyone run into this kind of issue previously?

Guessing there must be a simple solution.

In the meantime will keep looking for alternative solutions.

Any thought greatly appreciated.


Solution

  • Since react-intl uses Intl.NumberFormat under the hood, you might be able to use formatToParts to extract just the currency symbol, for example

    const symbol = Intl.NumberFormat('en-US', {
        style: 'currency',
        currencyDisplay: 'narrowSymbol',
        currency: 'USD'
      })
      .formatToParts(0)
      .filter(part => part.type === 'currency')
      .map(part => part.value)
      .join('')
    
    console.log(symbol)

    Although, depending on the required browser support, it might require a polyfill.