How to translate a widget's labels

I need to build a search page for a multilingual web app. For that matter, I wanted to use InstantSearch.js’ widgets such as “The refinement list widget”. The data for all languages will be the same, I need only to change interface depending on the user’s language. My question is the following.

If I submit data to the algolia in the following shape:

{
    "title": "Hello World",
    "categories": ["Peace", "Love", "Joy"]
} 

Will I be able to translate labels for the category widget that I will build with InatantSearch.js or not? e.g. If user language is English, then the category widget will look like:

Choose category:

  • Peace
  • Love
  • Joy

But, when user language is French, the widget will look like this:

Choisissez une catégorie:

  • Paix
  • Amour
  • Joie

You can use the transformData option of the widget!

Thank you for your help. Can you please a little bit elaborate on the matter of translation. I have read the docs, but still not sure how to accomplish it. I see that the transformData parameter works in conjunction with the template parameter. What does it mean? Should I first provide a template and then transformData, or I can just provide transformData?

You can find an example of the transformData option in the documentation.

Each transformData property is a function that gets called before the corresponding template gets computed. Each of these properties must be given the name of the template for which you want the data to be overridden. It’s in these functions that you want to update the data to display depending on your user’s language.

Hope it’s clear enough!

1 Like

Hey @said.akh,

What I suggest doing is the following:

const translationTable = {
  fr: {
    Peace: "Paix",
    Love: "Amour",
    Joy: "Joie",
    Samsung: "le Sam Sung",
    HP: "hache pée",
    "Insignia™": "in signe"
  }
};

const activeLanguage = "fr";

search.addWidget(
  instantsearch.widgets.refinementList({
    container: document.querySelector("#brand"),
    attributeName: "brand",
    transformData(data) {
      data.highlighted =
        translationTable[activeLanguage][data.highlighted] || data.highlighted;
      return data;
    }
  })
);

So you need some table for the translations (you can use crowdin for that). Beware that in the default template for refinementList, you need to use highlighted (so that there’s only one template, and no specific one if the searchbox is there).

I made a small demo here: https://codesandbox.io/s/4xr4505r27.

Your other options are:

  1. have separate indices for each language
  2. store just a translation ID instead of a whole string of a language in the data