Internationalization
You can use Rails internationalization (i18n) in your client code.
-
Set
config.i18n_dirinconfig/initializers/react_on_rails.rb:# Replace the following line by the directory containing your translation.js and default.js files. config.i18n_dir = Rails.root.join("PATH_TO", "YOUR_JS_I18N_FOLDER")If you do not want to use the YAML files from
Rails.root.join("config", "locales")and installed gems, you can also setconfig.i18n_yml_dir:# Replace the following line by the location of your client i18n yml files # Without this option, all YAML files from Rails.root.join("config", "locales") and installed gems are loaded config.i18n_yml_dir = Rails.root.join("PATH_TO", "YOUR_YAML_I18N_FOLDER") -
Add that directory (or just the generated files
translations.jsonanddefault.json) to your.gitignore. -
The locale files must be generated before building (e.g.,
npm run build,yarn build, orpnpm build).Option A: Direct Ruby API (best when you have a custom
bin/devscript or multiple build steps)Use the
ReactOnRails::Locales.compilemethod directly in yourbin/devscript:# In bin/dev require_relative "../config/environment" # Generate locales using direct Ruby API (faster than rake task) ReactOnRails::Locales.compile if ReactOnRails.configuration.i18n_dir.present?Benefits:
- Faster execution (no shell spawning overhead)
- Better version manager compatibility (mise, asdf, rbenv)
- Single place to manage all precompile tasks
- Can be combined with other build steps in one script
To force regeneration:
ReactOnRails::Locales.compile(force: true)Option B: Rake task (simplest for projects using
precompile_hookor one-off generation)Use
rake react_on_rails:localefrom the command line:bundle exec rake react_on_rails:locale # Subsequent calls will skip if already up-to-dateTo force regeneration:
bundle exec rake react_on_rails:locale force=trueThe locale generation is idempotent - it will skip generation if files are already up-to-date. This makes it safe to call multiple times without duplicate work.
Recommended: Use Shakapacker's precompile_hook with bin/dev (React on Rails 16.2+, Shakapacker 9.3+)
Configure the idempotent task in
config/shakapacker.ymlto run automatically before webpack:# config/shakapacker.yml default: &default precompile_hook: 'bundle exec rake react_on_rails:locale'With this configuration,
bin/devwill:-
Run the precompile hook once before starting development processes
-
Set
SHAKAPACKER_SKIP_PRECOMPILE_HOOK=trueto prevent duplicate execution -
Pass the environment variable to all spawned processes (Rails, webpack, etc.)
TIP
For HMR with SSR setups (two webpack processes), use a script-based hook instead of a direct command. Script-based hooks can include a self-guard that prevents duplicate execution regardless of Shakapacker version:
#!/usr/bin/env ruby # bin/shakapacker-precompile-hook exit 0 if ENV["SHAKAPACKER_SKIP_PRECOMPILE_HOOK"] == "true" system("bundle", "exec", "rake", "react_on_rails:locale", exception: true)Then configure:
precompile_hook: 'bin/shakapacker-precompile-hook'Upgrading existing apps
If your app already uses a direct command hook:
precompile_hook: 'bundle exec rake react_on_rails:locale'switch to
precompile_hook: 'bin/shakapacker-precompile-hook'and place the self-guard near the top of that script:exit 0 if ENV["SHAKAPACKER_SKIP_PRECOMPILE_HOOK"] == "true"This keeps locale generation reliable in SSR + HMR environments across Shakapacker versions.
This eliminates the need for sleep hacks and manual coordination in
Procfile.dev. See the Process Managers documentation for details.Alternative: Manual coordination
For development, you can adjust your startup scripts (
Procfiles) so that they runbundle exec rake react_on_rails:localebefore running any Webpack watch process (e.g.,npm run build:development,yarn run build:development, orpnpm run build:development).If you are not using the React on Rails test helper, you may need to configure your CI to run
bundle exec rake react_on_rails:localebefore any Webpack process as well.NOTE
If you try to lint before running tests, and you depend on the test helper to build your locales, linting will fail because the translations won't be built yet.
The fix is either:
- to run the rake task to build the translations before running the lint command, or
- to run the tests first.
-
If your locale files (or one of the gems locale files) contains unsafe YAML, you may need to configure
config.i18n_yml_safe_load_optionsif you can't fix such YAML files properly.config.i18n_yml_safe_load_options = { permitted_classes: [Symbol] }
By default, the locales are generated as JSON, but you can also generate them as JavaScript with react-intl support:
-
Specify the i18n output format in
config/initializers/react_on_rails.rb:config.i18n_output_format = "js" -
Add
react-intl&intltoclient/package.json, and remember to runbundle installand your package manager's install command (e.g.,npm install,yarn install, orpnpm install). The minimum supported versions are:"dependencies": { ... "intl": "^1.2.5", "react-intl": "^2.1.5", ... } -
In React, you need to initialize
react-intl, and set its parameters:... 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'; ... // Initialize 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) } )
Notes
- See why using JSON can perform better compared to JS for large amounts of data https://v8.dev/blog/cost-of-javascript-2019#json.
- See Support for Rails' i18n pluralization #1000 for a discussion of issues around pluralization.
- Outdated: You can refer to react-webpack-rails-tutorial and PR #340, committed for a complete example.