Skip to main content

Currency internationalization

Maksim Sharipov

Maksim Sharipov

Maintainer of eo-locale

In this article we consider how to create clear and reusable component Money. For many websites it is actual issue to display prices in different currencies and for different languages. It helps to be more friendly with customers from any country.

Let's figure requirements for those component:

  • Ability to pass currency
  • Ability to pass language, because for different languages we use different numeric format
  • Mode of currency display

Actually, with @eo-locale/react it is quite simple issue.

I am a big fan of TypeScript and all examples will use it.

import { Numeric } from '@eo-locale/react';
interface MoneyProps extends Intl.NumberFormatOptions {
amount: number;
language: string;
}
export const Money: React.FC<MoneyProps> = ({
amount,
language,
...shared
}) => {
return (
<Numeric
{...shared}
language={language}
style="currency"
value={amount}
/>
);
};

Interface MoneyProps extends interface Intl.NumberFormatOptions, therefore we can use any of standard params from Intl.NumberFormat.

For example, with next props:

import { Money } from '...somewhere';
const SomeComponent: React.FC = () => {
return <Money currency="usd" language="en" value={1000} />;
};

Component will display $1,000.00

For change mode of currency display, set currencyDisplay property. It can be symbol, code or name. By default symbol.

import { Money } from '...somewhere';
const SomeComponent: React.FC = () => {
return (
<Money currency="usd" currencyDisplay="name" language="en" value={1000} />
);
};

Component will display 1,000.00 US dollars

If you want to show only one fraction digit, just pass maximumFractionDigits and minimumFractionDigits property.

import { Money } from '...somewhere';
const SomeComponent: React.FC = () => {
return (
<Money
currency="usd"
language="en"
value={1000}
maximumFractionDigits={1}
minimumFractionDigits={1}
/>
);
};

Component will display $1,000.0

How to translate input placeholder

Maksim Sharipov

Maksim Sharipov

Maintainer of eo-locale

Translate input placeholder is quite common task. Let's consider how we can do it with eo-locale.

import { TranslationsProvider, useTranslator } from '@eo-locale/react';
const LOCALES = [{
language: 'en',
messages: {
hello: 'Hello World!',
}
}]
function App() {
return (
<TranslationsProvider language="en" locales={LOCALES}>
<SomeComponent />
</TranslationsProvider>
);
}
function SomeComponent() {
const translator = useTranslator();
return <input placeholder={translator.translate('hello')} />
}