When it comes to internationalization of your project, the hassle of choosing the right tool to start with can cause you some headache. This article is just right for you if you’re looking for a powerful solution but yet simple to implement to get your project translation up and running quickly. React-I18next is a localization framework specialized for React and React Native.

 

1. Where should I start?

 

First thing first, make sure you’re in the right folder and install i18next packages. In your terminal, run the command above. After that, open your package.json file and check in the dependencies if you have both packages. I include here my version of “i18next”: 15.0.7 and “react-i18next”: 10.5.2 just to make sure you have the same working versions.

 

2. Configuration File

Create a file named i18n.js in your src folder and use the following code.

 

i18next provisions users with great features such as browser language detector option. However, in this context, I prefer to set the language for user based on user info I receive back from calling user API so I have commented the LanguageDetector out.

 

3. Translations keys

• Create a folder called locales and create a json file for each language you need in the project.

• Inside the json file, you create different namespaces and key-value pairs for each translation key. In the example, I have two namespaces which are “common” and “modal”. In the newModal, I have the header key with the value containing variable called “item” with the format lowercase (set up format in the configuration file).

 

• When you add a json file for a new language, make sure it has the same format with the same namespaces and keys, the only difference stays in your value with different values for different languages.

 

4. Usage

Now when you have all the boilerplates, let’s get our work done. There are a few ways you can use i18next and below is to demonstrate you with the use of HOC. First you import withTranslation HOC from react-i18next, then you load single or multiple namespaces as params of withTranslation then use it to wrap your component. From there, the Header component gets access to t function and i18 instance via props. Use t function to translate the content by specifying the namespace and the key.


As mentioned, it’s simple and quick. I will link here react-i18next documentation for your further use cases.

https://react.i18next.com