Skip to content

Latest commit

 

History

History
90 lines (76 loc) · 2.68 KB

i18n.md

File metadata and controls

90 lines (76 loc) · 2.68 KB

How to add I18n

Here's a summary of adding I18n functionality with ReactOnRails.

You can refer to react-webpack-rails-tutorial for a complete example.

  1. Add react-intl to client/package.json, and remember to bundle && npm install
"dependencies": {
  ...
  "intl": "^1.2.5",
  "react-intl": "^2.1.5",
  ...
}
  1. In client/webpack.client.base.config.js, set react-intl as an entry point.
module.exports = {
  ...
  entry: {
    ...
    vendor: [
      ...
      'react-intl',
    ],
    ...
  1. ReactOnRails uses locale files as you did before in Rails: config/locales/*.yml. Therefore, you don't need to create additional local files.

  2. Update settings in config/initializers/react_on_rails.rb to what you need:

# 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")
  1. Add following lines to config/application.rb, this will help you to generate translations.js & default.js automatically when you starts the server.
module YourModule
  class Application < Rails::Application
    ...
    config.after_initialize do
      ReactOnRails::LocalesToJs.new.convert
    end
  end
end
  1. In React, you need to initialize react-intl, and set parameters for it.

translations.js: All your locales in json format.

default.js: [1] defaultLocale is your default locale, like "en". [2] defaultMessages is the place where you can get your local values with localeKeyInCamelForm, and it also contains fallback when something went wrong.

There is no need to track and lint translations.js & default.js, and you can add them to .gitignore and .eslintignore.

...
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) }
)