multilingualreact-i18nextreact-intl

What is the best way to build a multi-languages website with React


I want to build a multi-languages website using react and nodejs, so, I'm asking about the best external module to use and the way to implement it.

Comparing @lingui/core vs. i18n vs. i18next vs. react-i18next vs. react-intl


Solution

  • Since You are building a Reactjs App, there are quite a few i18n packages to choose from. Personally, I recommend Lingui, because of its simplicity.

    It uses a macro called <Trans>Translate this...</Trans> for code translation and then expand it at compile time.

    One good reason why I like them is that they don't force you to provide the id of each text you want to translate. You can just use the macro and be able to keep your code as natural as possible and not have to remember all the ids of each translatable word.

    Here is their documentation on how to install it

    yarn add --dev @lingui/cli @lingui/macro
    yarn add @lingui/react
    

    Then you create a config file lingui.config.json

    /** @type {import('@lingui/conf').LinguiConfig} */
    module.exports = {
       locales: ["en", "cs", "fr"],
       sourceLocale: "en",
       catalogs: [{
          path: "src/locales/{locale}/messages",
          include: ["src"]
       }],
       format: "po"
    }
    

    You can then add your scripts to the package.json

    {
       "scripts": {
          "extract": "lingui extract",
          "compile": "lingui compile"
       }
    }
    

    Then you can be able to use the Macro for translatable texts

    import { Trans } from "@lingui/macro"
    
    function render() {
      return (
        <>
          <h1><Trans>LinguiJS example</Trans></h1>
          <p><Trans>Hello <a href="/profile">{name}</a>.</Trans></p>
        </>
      );
    }
    

    You can see more in their documentation here.