Skip to content

Localized

Stanisław Małolepszy edited this page Jul 7, 2020 · 10 revisions

In @fluent/react, localizable elements can be wrapped in the Localized component.

Identifier

The id prop should be the unique identifier of the translation.

import { Localized } from '@fluent/react';

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

Attributes

Attributes defined in the translation will be applied to the wrapped element only if the attrs prop is defined. attrs should be an object with attribute names as keys and booleans as values. By default, if attrs is not passed, no attributes will be set.

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

Variables

You can also pass arguments to the translation in the vars prop:

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

Fallback String

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.

Markup

Translations can include simple HTML markup. @fluent/react will match them with elements passed to the elems prop to <Localized>. The contents of the passed elements will be replaced by the localizable content found in the markup the translation. This mechanism is called React Overlays.

<Localized
    id="create-account"
    elems={{
        confirm: <button onClick={createAccount}></button>,
        cancel: <Link to="/"></Link>
    }}
>
    <p>{'<confirm>Create account</confirm> or <cancel>go back</cancel>.'}</p>
</Localized>

Declarative and Imperative APIs

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 or the useLocalization hook.

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" attrs={{title: true}}>
    <DocumentTitle></DocumentTitle>
</Localized>