Here's a summary of adding the I18n functionality.
You can refer to react-webpack-rails-tutorial and PR #340, commmited for a complete example.
- Add
react-intl
&intl
toclient/package.json
, and remember tobundle && yarn install
.
"dependencies": {
...
"intl": "^1.2.5",
"react-intl": "^2.1.5",
...
}
- Add
config.i18n_dir
inconfig/initializers/react_on_rails.rb
react-intl
requires locale files in json format. React on Rails will generate translations.js
& default.js
automatically after you configured your config.i18n_dir
in config/initializers/react_on_rails.rb
.
# Replace the following line to the location where you keep translation.js & default.js.
config.i18n_dir = Rails.root.join("PATH_TO", "YOUR_JS_I18N_FOLDER")
Optionally you can also set config.i18n_yml_dir
if you do not what to use all the locale files from rails.
# Replace the following line to the location where you keep your client i18n yml files
config.i18n_yml_dir = Rails.root.join("PATH_TO", "YOUR_YAML_I18N_FOLDER")
translations.js
: All your locales in json format.
default.js
: Default settings in json format.
-
Add
translations.js
anddefault.js
to your.gitignore
and.eslintignore
. -
Javascript locale files must be generated before
yarn build
.
Once you setup config.i18n_dir
as in the previous step, react_on_rails will automatically do this for testing (if using the ReactOnRails::TestHelper.configure_rspec_to_compile_assets
and for production deployments if using the default precompile rake hook. For development, you should adjust your startup scripts (Procfiles) so that they run bundle exec rake react_on_rails:locale
before running any webpack watch process (yarn run build:development
).
- In React, you need to initialize
react-intl
, and set parameters for it.
...
import { addLocaleData } from 'react-intl';
import en from 'react-intl/locale-data/en';
import de from 'react-intl/locale-data/de';
import { translations } from 'path_to/i18n/translations';
import { defaultLocale } from 'path_to/i18n/default';
...
// Initizalize all locales for react-intl.
addLocaleData([...en, ...de]);
...
// set locale and messages for IntlProvider.
const locale = method_to_get_current_locale() || defaultLocale;
const messages = translations[locale];
...
return (
<IntlProvider locale={locale} key={locale} messages={messages}>
<CommentScreen {...{ actions, data }} />
</IntlProvider>
)
// In your component.
import { defaultMessages } from 'path_to/i18n/default';
...
return (
{ formatMessage(defaultMessages.yourLocaleKeyInCamelCase) }
)