Add multiple languages to your React app with i18next

Install the needed packages

Install i18next

yarn add i18next \
  react-i18next \
  i18next-http-backend \
  i18next-browser-languagedetector

Configuration

Add Suspense

Wrap your code with <Suspense /> like the following:

// file: src/index.js
(...)
ReactDOM.render(
    <Suspense fallback="loading">
        <Router>
            <Switch>
                <Route 
                  exact 
                  path='/login' 
                  component={Login}
                />
                <Route component={App}/>
                <ToastContainer/>
            </Switch>
        </Router>
    </Suspense>,
    document.getElementById('root')
)

Initializing i18next in your app

Place the following initilisation code in a file i18n.js

// file: ./js/helpers/i18n.js
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import Backend from 'i18next-http-backend'
import LanguageDetector from 'i18next-browser-languagedetector'

i18n
  .use(Backend)
  .use(LanguageDetector)
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    fallbackLng: 'en',
    debug: false,

    backend: {
      loadPath: '/locales/{{lng}}.json',
      // path to post missing resources
      addPath: '/locales/add/{{lng}}.json',
    },

    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    }
  });

export default i18n;

The parser

Add the config file in your root directory: ./i18next-parser.config.js

This will:

  • put the translatable strings inside ./public/locales/<language>.json
  • support en and nl countrycodes for language
  • use the key (the translatable string) as the translation when a new translatable string is found
// file: ./i18next-parser.config.js
module.exports = {
  
  // see below for more details
  lexers: {
    // hbs: ['HandlebarsLexer'],
    // handlebars: ['HandlebarsLexer'],

    htm: ['HTMLLexer'],
    html: ['HTMLLexer'],

    // mjs: ['JavascriptLexer'],
    js: ['JavascriptLexer'], // if you're writing jsx inside .js files, change this to JsxLexer
    ts: ['JavascriptLexer'],
    jsx: ['JsxLexer'],
    tsx: ['JsxLexer'],

    default: ['JavascriptLexer']
  },

  locales: ['en', 'nl'],
  // An array of the locales in your applications

  output: 'public/locales/$LOCALE.json',
  // output: 'locales/$LOCALE/$NAMESPACE.json',
  // Supports $LOCALE and $NAMESPACE injection
  // Supports JSON (.json) and YAML (.yml) file formats
  // Where to write the locale files relative to process.cwd()

  useKeysAsDefaultValue: true,
  // Whether to use the keys as the default value; ex. "Hello": "Hello", "World": "World"
  // This option takes precedence over the `defaultValue` and `skipDefaultValues` options

  verbose: true,
  // Display info about the parsing including some stats
}

Scan the code for translatable strings

Install the scanner application with npm.

npm install -g i18next-parser

Assuming that you placed the config file in the root of your project (i18next-parser.config.js), run the following command:

i18next --config ./i18next-parser.config.js \
    'src/**/*.js' \
    '!src/js/bootstrap.min.js' 

--config provide the path to your config. In this example it is not needed as the configuration has the default name and is in the default location
src/**/*.js provide the glob which finds all your *.js files. Add what you need (.ts, .jsx, etc.)
!src/js/bootstrap.min.js an example of how to exclude a certain file

Now you can find the translatable strings in the following files: ./public/locales/<language>.json

Change the language in the application

Change the language with i18next

// file: ./index.js
import './js/helpers/i18n'
import i18next from 'i18next'

...

// change the language
i18next.changeLanguage('nl')

Click Here to Leave a Comment Below

Leave a Reply: