module-intl
v1.3.2
Published
Intl helper functions for React Web App
Downloads
2
Readme
Intl as a Module
Simple Intl for React Web App
Steps
- Installation
- Initialization
- Intl Polyfill
Installation
npm install --save react-intl intl module-intl
Initialization
You can flexibily initialize the module by yourself.
It is suggested to use separated files like messages.json
and intl-config.js
for managing messages and language config.
messages.json
{
"en": {
"title": "English Title",
"home.welcome": "Welcome to the English version website"
},
"zh": {
"title": "中文標題",
"home.welcome": "歡迎來到中文網站"
}
}
./initializers/intl/index.js
import ModuleIntl from 'module-intl';
import MESSAGES from './messages';
const DEFAULT_LOCALE = 'en';
const DISPLAY_NAMES = {
en: 'English',
zh: '中文',
};
export default new ModuleIntl(DEFAULT_LOCALE, DISPLAY_NAMES, MESSAGES);
Intl Polyfill
You can start using the intl module and inject intl polyfill in your app entry point to support Browser like Safari.
It is important to import the intl polyfill before rendering your app.
import intl from './initializers/intl';
import render from './render';
intl.polyfill(() => render());
Working together with React Intl
import { IntlProvider } from 'react-intl';
import intl from './initializers/intl';
export default (
<IntlProvider
locale={intl.locale}
messages={intl.translation}
>
{/* Your Child Component */}
</IntlProvider>
);
Notes on React Intl
import { FormattedMessage } from 'react-intl';
<FormattedMessage
id="travel"
defaultMessage="Travel"
/>
Usages
Getters
- intl.locale: Get the language code of current language
- intl.locales: Get all language codes
- intl.name: Get the display name of current language
- intl.names: Get all display names of language for Language Menu
- intl.translation: Get the translation of current locale
- intl.displayName: Get the displayName of a given locale
Setters
- intl.locale = 'zh';
Methods
- intl.polyfill(callback): Inject Intl polyfill before rendering to support Browser like Safari