React
Localize React apps with Transifex Native
You can easily localize React components using the @transifex/react library extension. This library extends the functionality of Transifex Native JavaScript SDK.
Related packages:
Checkout a quick overview video:
Installation
Install the extension library using:
npm install @transifex/native @transifex/react @transifex/cli --save
Usage
T
Component
T
Componentimport React from 'react';
import { T } from '@transifex/react';
function Example() {
return (
<div>
<T _str="Hello world" />
<T _str="Hello {username}" username={user} />
</div>
);
}
Available optional props:
Prop | Type | Description |
---|---|---|
_context | String | String context, affects key generation |
_key | String | Custom string key |
_comment | String | Developer comment |
_charlimit | Number | Character limit instruction for translators |
_tags | String | Comma separated list of tags |
The T-component can accept React elements as properties and they will be
rendered properly, ie this would be possible:
<T
_str="A {button} and a {bold} walk into a bar"
button={<button><T _str="button" /></button>}
bold={<b><T _str="bold" /></b>} />
This will render like this in English:
A <button>button</button> and a <b>bold</b> walk into a bar
And like this in Greek:
Ένα <button>κουμπί</button> και ένα <b>βαρύ</b> μπαίνουν σε ένα μπαρ
Assuming the translations look like this:
source | translation |
---|---|
A {button} and a {bold} walk into a bar | Ένα {button} και ένα {bold} μπαίνουν σε ένα μπαρ |
button | κουμπί |
bold | βαρύ |
The main thing to keep in mind is that the _str
property to the T-component
must always be a valid ICU messageformat template.
UT
Component
UT
Componentimport React from 'react';
import { UT } from '@transifex/react';
function Example () {
return (
<div>
<UT _str="Hello <b>{username}</b>" username={user} />
<p>
<UT _str="Hello <b>{username}</b>" _inline username={user} />
</p>
</div>
)
}
UT
has the same behaviour as T
, but renders source string as HTML inside a
div
tag.
Available optional props: All the options of T
plus:
Prop | Type | Description |
---|---|---|
_inline | Boolean | Wrap translation in span |
Note: If you supply React elements as properties to the UT
component, it
will misbehave by rendering [object Object]
. Only use React elements as
properties with the T
component.
useT
hook
useT
hookMakes the current component re-render when a language change is detected and
returns a t-function you can use to translate strings programmatically.
You will most likely prefer to use the T
or UT
components over this, unless
for some reason you want to have the translation output in a variable for
manipulation.
import React from 'react';
import { useT } from '@transifex/react';
function Capitalized() {
const t = useT();
const message = t('Hello world');
return <span>{message.toUpperCase()}</span>;
}
Optionally useT
can take as param a custom Native Instance:
import { useT } from '@transifex/react';
import { createNativeInstance } from '@transifex/native';
const customTX = createNativeInstance({
token: 'token',
secret: 'secret',
});
function Component() {
const t = useT(customTX);
// ...
}
useLanguages
hook
useLanguages
hookReturns a state variable that will eventually hold the supported languages of
the application. Makes an asynchronous call to the CDS.
import React from 'react';
import { useLanguages } from '@transifex/react';
function LanguageList () {
const languages = useLanguages();
return (
<ul>
{languages.map(({ code, name }) => (
<li key={code}>
<strong>{code}</strong>: {name}
</li>
))}
</ul>
);
}
Optionally useLanguages
can take as param a custom Native Instance:
import { useT } from '@transifex/react';
import { createNativeInstance } from '@transifex/native';
const customTX = createNativeInstance({
token: 'token',
secret: 'secret',
});
function Component() {
const languages = useLanguages(customTX);
// ...
}
useLocale
hook
useLocale
hookReturns a state variable with the currently selected locale.
import React from 'react';
import { useLocale } from '@transifex/react';
function DisplayLocale () {
const locale = useLocale();
return (
<p>Currently selected locale is {locale}</p>
);
}
Optionally useLocale
can take as param a custom Native Instance:
import { useT } from '@transifex/react';
import { createNativeInstance } from '@transifex/native';
const customTX = createNativeInstance({
token: 'token',
secret: 'secret',
});
function Component() {
const locale = useLocale(customTX);
// ...
}
useTX
hook
useTX
hookReturns a state variable with the Native instance.
import React from 'react';
import { useTX } from '@transifex/react';
function SetLocale () {
const tx = useTX();
return (
<button onClick={() => tx.setCurrentLocale('el')}>
Set to Greek
</button>
);
}
LanguagePicker
component
LanguagePicker
componentRenders a <select>
tag that displays supported languages and switches the
application's selected language on change.
Uses useLanguages
and useLocale
internally.
import React from 'react';
import { T, LanguagePicker } from '@transifex/react';
function App () {
return (
<div>
<T _str="This is a translatable message" />
<LanguagePicker />
</div>
);
}
Accepts properties:
Prop | Type | Description |
---|---|---|
className | String | The CSS class that will be applied to the <select> tag |
If you want something different than a <select>
, it should be easy to write
your own language picker using useLanguages
:
import React from 'react';
import { tx } from '@transifex/native';
import { useLanguages, useLocale } from '@transifex/react';
function MyLanguagePicker () {
const languages = useLanguages();
const locale = useLocale();
return (
<>
{languages.map(({ code, name }) => (
<button key={code} onClick={() => tx.setCurrentLocale(code)}>
{name} {locale === code ? '(selected)' : ''}
</button>
))}
</>
);
}
useTranslations
hook - aka Lazy Loading
useTranslations
hook - aka Lazy LoadingFetches translations tagged with a specific combination of tags when a
component first renders. This way, you can pull translations from the CDS in
batches and only when needed:
tx.init({ token: ..., filterTags: 'home' });
export default function App() {
return (
<>
<T _str="This will be translated as soon as possible" _tags="home" />
{someCondition() && <Inner />}
</>
);
}
function Inner() {
useTranslations('inner');
return <T
_str="This will be translated when the inner component is rendered"
_tags="inner" />;
}
The hook returns a boolean state variable called ready
that you can use to
handle a loading state:
function Inner() {
const { ready } = useTranslations('inner');
if (!ready) { return 'Loading...'; }
return <T
_str="This will be translated when the inner component is rendered"
_tags="inner" />;
}
If you don't handle the loading state, the source string will be rendered
first and then replaced with the translation when it becomes available.
You can also use the hook in parent components that don't need the tagged
translations themselves. This will make the translations available sooner for
child components that may potentially need them:
tx.init({ token: ..., filterTags: 'home' });
export default function App() {
const { ready: innerReady } = useTranslations('inner');
return (
<>
<T _str="This will be translated as soon as possible" _tags="home" />
{someCondition() && <Inner ready={innerReady} />}
</>
);
}
function Inner({ ready }) {
if (!ready) { return 'Loading...'; }
return <T
_str="This will be translated when the inner component is rendered"
_tags="inner" />;
}
Optionally useTranslations
can take as a second param a custom Native Instance:
import { useT } from '@transifex/react';
import { createNativeInstance } from '@transifex/native';
const customTX = createNativeInstance({
token: 'token',
secret: 'secret',
});
function Component() {
const { ready } = useTranslations('inner', customTX);
// ...
}
TXProvider
provider
TXProvider
providerIf you need to use more than one Transifex Native instances - like for example if you have a component library - you can use this provider to pass the desired instance to the children components.
import { tx, createNativeInstance } from '@transifex/native';
import { TXProvider, LanguagePicker, T } from '@transifex/react';
const myOtherTXInstance = createNativeInstance();
myOtherTXInstance.init({ token: 'othertoken' })
tx.init({
token: 'token',
});
// Make tx aware of the other instances so they can be synced when changing
// language
tx.controllerOf(myOtherTXInstance);
export default function App() {
return (
<>
<LanguagePicker />
<TXProvider instance={myOtherTXInstance}>
<T _str="Hello {username}" username="John" />
</TXProvider>
<T _str="Hello World" />
</>
);
}
Best practices
If your website is designed around multiple individual SPAs, you can take advantage of a Transifex Native feature, called Content Splitting, in order to optimize the bundle size transferred over the air to the client’s app.
Updated 11 months ago