Translation

Translation

Next Built in Internalization

Next.js has built-in support for internationalized (i18n) routing since v10.0.0. You can provide a list of locales, the default locale, and domain-specific locales and Next.js will automatically handle the routing.

Next.js automatically matches the route with the actual local. example: /fr/login will be set a locale property on the Next.js router Object .

React-Intl library

Translation Package that matches the content with the locale context. Official website & docs (opens in a new tab)

This package needs to wrap around out root App component.

  <IntlProvider locale={usersLocale} messages={translationsForUsersLocale}>
    <App />
  </IntlProvider>,

Implementation and Usage

First, we declare our 'locale' inside a config file next-i18next.config.js that needs to be imported inside next.config.js.

next-i18next.config.js

module.exports = {
  i18n: {
    defaultLocale: 'en',
    locales: ['en', 'fr'],
  },
};

Also, _app.tsx file, the root of the app, needs to be make the app contextualizing the react-Intl Provider

src/pages/_app.tsx

 
import en from '../utils/locales/en/common.json';
import fr from '../utils/locales/fr/common.json';
 
const messages = {
  en,
  fr,
};
..
..
  <IntlProvider locale={locale} messages={messages[locale]}>
          <Component {...pageProps} />
        </IntlProvider>
      }

Now, we need to declare Messages or Translation folder: src/utils/locales/en

src
/
└── utils
    ├── locales
    │   ├── en
    │   │   └── common.json
    │   └── fr
    │       └── common.json
...

Usage:

inside common.json we create the exquivalent of 'textOriginal'

{
  "Add": "Ajouter",
  "Filters": "Filtres",
  "Home": "Accueil",
  ..
  }

Then inside project component/pages, we use the useTranslation custom hook.

import useTranslation from '@/hooks/shared/translation/useTranslation';
 
function component(){
 
const {t}  = useTranslation()
..
...
(
    <div>
 
    <section>{t(`textOriginal`)}</section>
 
    </div>
)
 
}
 

Language Selection Custom component

It is a component that renders a select component to choose the language

<LangSelector />