intl-react
@cloudflare/intl-react
This is a collection of react wrappers for i18n at Cloudflare.
Installation
$ npm install @cloudflare/intl-react
IntlProvider
This is a wrapper around an instance of Translator of intl-core
.
It takes three optional arguments:
- locale
- phrases
- translator
If translator
isn't provided, IntlProvider
will take the translator
from a
parent IntlProvider
if present, otherwise it will instantiate new one.
if locale
is present, it is set as the current locale of the translator
. if
phrases
is present, the translator
's extend
method is called with
phrases
import { I18nProvider, Trans } from '@cloudflare/intl-react';
const Component = () => (
<I18nProvider>
<Trans id='foo'/>
</IntlProvider>,
);
export default Component;
OR ...
import { I18nProvider, Trans } from '@cloudflare/intl-react';
import { Translator, ESupportedLocales } from '@cloudflare/intl-core';
import phrases from './phrases.json';
const translator = new Translator();
const Component = () => (
<I18nProvider translator={translator} phrases={phrases} locale={ESupportedLocales.de_DE}>
<Trans id='foo'/>
</IntlProvider>,
);
export default Component;
IntlLoader
This is a wrapper around IntlProvider
.
It is to be used in cases where the phrases catalog is loaded asyncronously.
It takes two arguments:
- locale (optional;)
- loadPhrases
If locale isn't provided, it will be the current locale of the translator object
residing above the component. If none exist it will be ESupportedLocales.en-US
by default.
The prop loadPhrases
, takes in locale
as a param and returns a promise,
resolving to the phrases catalog for that language.
import { I18nProvider, Trans, IntlLoader } from '@cloudflare/intl-react';
const loadPhrases = (locale) => import('./phrases.json')
const Component = () => (
<I18nProvider>
<IntlLoader loadPhrases={loadPhrases}>
<Trans id='foo'/>
</IntlLoader>
</IntlProvider>,
);
export default Component;
Trans
The Trans
component is a wrapper around the Translator
's t
function, which
itself provides the same api as Polyglot
's t
function.
Its props are:
- id: string (required) - the key for the phrase
- smartCount: number (optional) - polyglot's smart_count
- _: optional: string (optional) - default value for the phrase
- values: object (optional) - interpolation values
- applyMarkdown: boolean (optional) - default false - apply markdown
transformation to the translated string?
<Trans id="foo" />;
OR ...
<Trans id="foo" _="default value" />;
OR ...
<Trans id="foo" smartCount={2} />;
OR ...
<Trans id="foo" values={{ name: 'foo' }} />;
OR ...
<Trans id="foo" _="*default value*" applyMarkdown={true} />;
I18n
The I18n
component is the Consumer
part of the React Context providing the
translation library. As such it has follows React's Render Props pattern.
<I18n>
{translator => {
return <CustomComponent customAttribute={translator.t('some_key')} />;
}}
</I18n>;