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 thecomponents.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 thebefore_render
hook to configure i18n-js accordingly for each render call.
When using Rails 6, this will not work due to webpacker (I18n is not global). Here's my solution that should work with both server and client side rendering.
In config/application.rb:
(I don't like the anonymous class, but I couldn't work out in what file to put this class)
app/javascript/packs/server_rendering.js:
app/javascript/packs/application.js:
app/javascript/i18n-js/index.js.erb:
In application.html.erb I added
Somehow, this feels quite "hacky". If anyone has a better solution, please let me know.