Skip to content

Localized

Staś Małolepszy edited this page Oct 25, 2017 · 10 revisions

In fluent-react, localizable elements can be wrapped in the Localized component:

import { Localized } from 'fluent-react';

<Localized id="hello-world">
    <p>Hello, world!</p>
</Localized>

The id prop should be the unique identifier of the translation. Attributes defined in the translation will be applied to the wrapped element.

type-name
    .placeholder = Your name
<Localized id="type-name">
    <input
        type="text"
        placeholder="Your name"
        onChange={}
        value={}
    />
</Localized>

You can also pass arguments to the translation as $-prefixed props on Localized:

<Localized id="welcome" $username={name}>
    <p>{'Welcome, {$username}'}</p>
</Localized>

It's recommended that the contents of the wrapped component be a string expression. The string will be used as the ultimate fallback if no translation is available. It also makes it easy to grep for strings in the source code. In the future, it may be used for automatic extraction of source copy.

It's also possible to pass React elements as arguments to translations:

<Localized
    id="welcome"
    $linkA={
        <a href="http://example.com/A">A</a>
    }
    $linkB={
        <Localized id="link-to-b">
            <a href="http://example.com/B">B</a>
        </Localized>
    }>
    <p>{'Click { $linkA } or { $linkB}.'}</p>
</Localized>

Using <Localized> makes your code more declarative. fluent-react will automatically respond to the browser's language changes and re-translate all <Localized> elements. For cases when a one-off translation is sufficient (e.g. in a modal window or a push notification) you may want to use the withLocalization decorator.

The declarative nature of <Localized> synergizes well with other declarative components. For instance, it's easy to localize the document's title by combining react-document-title and <Localized>.

document
    .title = Welcome
<Localized id="document">
    <DocumentTitle></DocumentTitle>
</Localized>