i18n of React with Lingui.js #2
stereobooster
Posted on November 18, 2018
In this post, I want to show how to use Lingui.js to do i18n/l10n of React applications. I will use Node 10.10 and yarn
, but I guess npm
and other versions of Node would work too. The full source code is here. Each step of the tutorial is done as a separate commit, so you can trace all changes of the code.
Advanced usage
Language switcher
Simplest language switcher can be implemented this way:
import * as React from "react";
import { withI18n } from "@lingui/react";
const Navigation = ({ i18n, locales }) => (
<select selected={i18n.locale}>
{Object.keys(locales).map(locale => (
<option key={locale} onClick={() => i18n.activate(locale)} value={locale}>
{locales[locale]}
</option>
))}
</select>
);
export default withI18n(Navigation);
withI18n
is a HOC, which provides i18n
object. The same one which we pass to <I18nProvider i18n={i18n}>
.
i18n.locale
provides current locale.
i18n.activate
changes current locale.
Translate text without Trans
macro
import { I18n } from "@lingui/react";
import { t } from "@lingui/macro";
// ...
<I18n>
{({ i18n }) => (
<button onClick={() => alert(i18n._(t`You're looking good!`))}>
<Trans>Show motto of the day</Trans>
</button>
)}
</I18n>;
I18n
is a "Render Prop" component, which provides i18n
object. The same one which we pass to <I18nProvider i18n={i18n}>
.
i18n._
is a translation function, which will actually do the translation.
t
is a macro which is used by extract
command.
To provide default value for translation use comment:
i18n._(/* i18n: Default value for Hello {name} */ t`World`);
Plural
Use Plural
macro if you need to deal with numbers.
import { Plural } from "@lingui/macro";
// ...
<Plural
value={count}
_0="There're no books"
one="There's one book"
other="There're # books"
/>;
DateFormat
Use DateFormat
to format dates.
import { DateFormat } from "@lingui/macro";
// ...
<Trans>
Today is <DateFormat value={new Date()} />
</Trans>;
NumberFormat
Use NumberFormat
to format numbers.
import { NumberFormat } from "@lingui/macro";
// ...
<NumberFormat value={2000} format={{ style: "currency", currency: "USD" }} />
<NumberFormat value={0.2} format={{ style: "percent" }} />
Posted on November 18, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.