React i18next is an internationalization library for localizing applications.
ℹ️
Prerequisites
Before we begin, ensure that you have a working React app using react-i18next which is set up with Storybook 6.0 or newer. If you need resources to set these up, I’ve included some recommendations below:
To make your translations available in your stories, you’ll first need to expose your i18next instance to Storybook. Here’s an example of an i18next instance from the ./src/i18n.js file being used in my React app.
To expose this instance to Storybook, we can import it into the ./.storybook/preview.js file where Storybook holds its shared story configurations.
Now that Storybook has access to i18next, we need to share that with our stories. To do that we’re going to make a decorator to wrap our stories in.
Sweet! Our stories officially have access to our translations. If we change the lng defined in ./src/i18n.js you’ll see your stories reload in the new language.
Hardcoding your locale is annoying and won’t be helpful to anyone viewing your deployed Storybook, so let’s add a locale switcher to the Storybook toolbar. If you want to learn more about switchers, check out Yann Braga’s article on adding a theme switcher.
To do this, we can declare a global variable named locale in .storybook/preview.js and assign it to a list of supported languages to choose from.
Looking back at Storybook, we can now see that we have a “Locale” switcher added to the toolbar with the options we just set.
Now let’s update our decorator to change our locale when we select a new language.
Voila— a fully functioning locale switcher for your stories powered by react-i18next!
Some languages are not read from left to right like English is. Arabic, for example, is read from right to left. HTML has built-in support for this with the dir attribute.
First of all, let's add Arabic as an option in our locale switcher by adding an object into the items array of our globalTypes.
Using i18next’s dir(lng) function and languageChanged event, we can set the document direction for the selected locale.
Now when we set our storybook to Arabic, the document direction gets set to ”rtl” 🎉