Search⌘ K
AI Features

Translating Checkout

Explore how to add multi-language support for a Rails e-commerce checkout page with React components. Learn to use the i18n-js library to sync Rails translations with JavaScript, ensuring dynamic form elements display localized content. Understand configuring middleware, updating React JSX with I18n.t(), and translating error messages and model attributes to create a fully localized user experience.

Adding translation for order page

Now we’re entering the home stretch. The new order page is next:

HTML
<section class="depot_form">
<h1><%= t('.legend') %></h1>
<%= render 'form', order: @order %>
</section>
<%= javascript_pack_tag("pay_type") %>

Here’s the form that’s used on this page:

HTML
<%= form_with(model: order, local: true) do |form| %>
<% if order.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(order.errors.count, "error") %>
prohibited this order from being saved:</h2>
<ul>
<% order.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :name, t('.name') %>
<%= form.text_field :name, size: 40 %>
</div>
<div class="field">
<%= form.label :address, t('.address_html') %>
<%= form.text_area :address, rows: 3, cols: 40 %>
</div>
<div class="field">
<%= form.label :email, t('.email') %>
<%= form.email_field :email, size: 40 %>
</div>
<div id='pay-type-component'></div>
<div class="actions">
<%= form.submit t('.submit') %>
</div>
<% end %>

That covers the form elements that Rails is rendering, but what about the React-rendered payment details we added in Adding Fields Dynamically to a Form? Recall that, we had to create the HTML form elements inside React components, mimicking what Rails form helpers would do.

Since React is rendering our payment details components, not Rails, we need to make our translations available to React. This means they must be available in JavaScript. Happily, the i18n-js library will do just that.

This library will make a copy of our translations as a JavaScript object and provide an object called I18n that allows us to access them. Our React components will use that to provide localized strings for the dynamic form we created earlier. First, we’ll add it to our Gemfile:

Ruby
gem 'i18n-js'

Getting i18n-js to work requires a bit of configuration, so let’s do that before we start using it in our React components.

First, we’ll configure ...