i18next

Full tutorial with example code can be found on our blog.

Check blog post about i18next and React application localization in 3 steps.

Install dependencies

# Using NPM
npm install --save react-i18next i18next i18next-http-backend i18next-browser-languagedetector

# Using yarn
yarn add react-i18next i18next i18next-http-backend i18next-browser-languagedetector

Configure i18next

Create i18n.ts file with i18next configuration. This file will be imported in index.ts.

import i18n from 'i18next'
import Backend from 'i18next-http-backend'
import LanguageDetector from 'i18next-browser-languagedetector'
import { initReactI18next } from 'react-i18next'

const projectToken = "5e13e3019cff4dc6abe36009445f0883";
const loadPath = `https://cdn.simplelocalize.io/${projectToken}/_latest/i18next/{{lng}}/{{ns}}/_index`;

i18n
  .use(Backend)
  .use(LanguageDetector)
  .use (initReactI18next)
  .init({
    // default/fallback language 
    fallbackLng: 'en',
    ns: ["default"],
    defaultNS: "default",
    //detects and caches a cookie from the language provided
    detection: {
      order: ['queryString', 'cookie'],
      cache: ['cookie']
    },
    interpolation: {
      escapeValue: false
    },
    backend: {
      loadPath
    }
  })

export default i18n;

Enable i18next in application

Import i18n.ts file in index.ts by adding import './i18n'; Whole index.ts file should look like this:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import './i18n'; // import i18next configuration (!!)

ReactDOM.render (
  <React.StrictMode>
    <Suspense fallback={<div>Loading...</div>}>
        <App />
    </Suspense>
  </React.StrictMode>,
  document.getElementById('root')
);

Example usage

import React from "react";
import { useTranslation } from "react-i18next";

function App() {
  const { t, i18n } = useTranslation();
  return (
        <div>
          <p>
            {t("USE_BUTTONS_BELOW")}
          </p>
          <button onClick={() => i18n.changeLanguage("en")}>English</button>
          <button onClick={() => i18n.changeLanguage("es")}>Spanish</button>
        </div>
  );
}

export default App;

Use t function to get translation from given translation key

t("USE_BUTTONS_BELOW")

Switch languages with i18n.changeLanguage(language). i18n object comes from React Hook called useTranslations();

Full application code is available on Github. Visit simplelocalize/simplelocalize-i18next repository.