-
Notifications
You must be signed in to change notification settings - Fork 77
Localized
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 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>
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>