React Multi-lingual with react-i18next

Rick Lee
2 min readFeb 26, 2019

--

Photo by Vladislav Klapin on Unsplash

When we build an international web site, multi-lingual support is always one of the essential feature. Fortunately, if we use React, there are quite some awesome libraries that come in handy and react-i18next is one of the most popular open source libraries and here is simple example to get it started.

The very first thing is always to create a react app using create-react-app and install those necessary npm packages.

And here we put those translations to static json files and you can put it in Rest endpoint if you want.

Create assets directory in public folder.

And then create 2 simple translation files, one for English and one for traditional Chinese and put them in public/assets/i18n/translations folder.

The next step is to create the i18next configuration/initiation script. Let’s create a file, i18n.js, under the src directory:

Now let’s create 2 dummy components, one to show the “Hello” string and the other shows “Thank You”. The react-i18next library provides several ways to access translations, e.g., context API, hooks, HOC, etc. In the following sample codes, the Hello.js uses hooks and ThankYou.js uses HOC.

Now let’s create a simple language selector that contains a 2 radio buttons for us to choose between English and Traditional Chinese. For the following codes, you can see we can simply pass the locale name to the i18n.changeLanguage function to switch between languages.

Finally, let’s modify the App.js to show all the components we have created so far. You can see we use Suspense here, as the react-i18next loads locale resources file asynchronously and we have to wait until the loading is completed before we can use it.

The result!

Github for source codes : https://github.com/rickcodetalk/test-react-i18next

--

--

Rick Lee

In love with programming and hosted a Cantonese programming Youtube channel — https://www.youtube.com/rickcodetalk