Skip to content

Instantly share code, notes, and snippets.

@seoyoochan
Forked from jhilden/README.md
Created March 17, 2016 22:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seoyoochan/78b686927ac1e8e871cb to your computer and use it in GitHub Desktop.
Save seoyoochan/78b686927ac1e8e871cb to your computer and use it in GitHub Desktop.
Setup for using i18n-js together with react-rails i18n-js for server side prerendering

When using react-rails for an internationalized app it makes a lot of sense to use i18n-js for translations, so that you can reuse the the strings from your rails app's .yml files (and all the tooling & services that exist around that).

When you use the prerender feature of react-rails you face 2 problems:

  • The first is that translation.js & i18n.js from i18n-js need to be loaded inside the server-side JS prerendering processes, which is achieved by loading them inside the components.js.
  • The second problem is the server processes need to be aware of the current locale of each HTTP request. This is done by adding a custom renderer and using the before_render hook to configure i18n-js accordingly for each render call.
require 'i18n_js_renderer'
module MyRailsApp
class Application < Rails::Application
config.react.server_renderer = React::ServerRendering::I18nJsRenderer
end
end
//= require i18n
//= require i18n/translations
//= require_tree ./components
module React
module ServerRendering
class I18nJsRenderer < SprocketsRenderer
def before_render(component_name, props, prerender_options)
super + "I18n.defaultLocale = '#{MyRailsApp::Application.config.i18n.default_locale}'; I18n.fallbacks = true; I18n.locale = '#{I18n.locale}';"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment