Skip to content

Instantly share code, notes, and snippets.

@luciaaldana
Last active February 2, 2023 12:28
Show Gist options
  • Select an option

  • Save luciaaldana/540d60b401bea06672f03ea01db80aab to your computer and use it in GitHub Desktop.

Select an option

Save luciaaldana/540d60b401bea06672f03ea01db80aab to your computer and use it in GitHub Desktop.
i18next React

i18next React

Install

npm install react-i18next i18next i18next-browser-languagedetector --save

yarn react-i18next i18next i18next-browser-languagedetector --save

i18next.js

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import translationEn from './translation.json';
import translationEs from './translation.json';

const fallbackLng = ['en'];
const availableLanguages = ['en', 'es'];

const resources = {
  en: {
    translation: translationEn,
  },
  es: {
    translation: translationEs,
  },
};

i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    resources,
    fallbackLng,
    detection: {
      checkWhitelist: true,
    },
    debug: false,
    react: {
      useSuspense: false,
    },
    whitelist: availableLanguages,
    interpolation: {
      escapeValue: false,
    },
  });

export default i18n;

index.js

Start i18next in the app index.

import React from 'react';
import ReactDOM from 'react-dom/client';
import "./i18nextInit";
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

There must be a translation file for each language with the same keys.

We will use these files in the resources of the i18next configuration as shown in the file above.

translation.json (es)

{
  "greeting": "Hola mundo",
}

translation.json (en)

{
  "greeting": "Hello world",
}

HOW TO USE

import { useTranslation } from 'react-i18next';

const App = () => {
  const { t } = useTranslation();
  return (
    <h1>{t('greeting')}</h1>
  )
}

Change language

i18next.changeLanguage(language);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment