Skip to content

Localized

Staś Małolepszy edited this page Dec 13, 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.

Translations can include simple HTML markup. fluent-react will match them with props to <Localized>. If the prop is a React element, its content will be replaced by the localizable content found in the markup the translation. This mechanism is called Overlays.

<Localized
    id="create-account"
    confirm={
        <button onClick={createAccount}></button>
    }
    cancel={
        <Link to="/"></Link>
    }>
    <p>{'<confirm>Create account</confirm> or <cancel>go back</cancel>.'}</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>