• Launch It
  • Posts
  • Switching Languages in React with i18next

Switching Languages in React with i18next

Setting up internationalization (i18n) in a React application using i18next.

Switching Languages in React with i18next

In this blog, I will guide you through the process of setting up internationalization (i18n) in a React application using i18next. We will cover the installation of necessary packages, configuration of i18next, and the creation of components to switch between languages dynamically.

Prerequisites

  • Basic knowledge of React and React hooks.

  • A React project set up (we will not cover setting up the React project itself).

Step 1: Install i18next and react-i18next

First, you need to install i18next and react-i18next in your project. These packages help integrate i18next with React.

npm install i18next react-i18next

Step 2: Configure i18next

Create a configuration file for i18next. This will include setting up the languages and initializing i18next with the appropriate options.

folder structure

I like to create index.ts file under the i18n directory (or any directory you prefer). I have created a Translations folder containing two translation files, one for Nepali and another for English. I will provide more details about this below.

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import eng from "./Translations/en.json";
import nep from "./Translations/ne.json";
import Session from "../Session";

import { SESSION_STORAGE_KEY as LanguageKey } from "../Language";

type SessionLanguage = {
  Language: string;
};

const userLanguage =
  (Session.get(LanguageKey) as SessionLanguage | null)?.Language ?? "en";

const resources = {
  en: eng,
  ne: nep,
};

i18n.use(initReactI18next).init({
  resources,
  lng: `${userLanguage}`,
  fallbackLng: "en",
  returnNull: false,
  keySeparator: false,
  interpolation: {
    escapeValue: false,
  },
});

export default i18n;

In this configuration:

  • We import the necessary modules.

  • We set up the initial language based on what is stored in the session storage.

  • We define our language resources (en for English and ne for Nepali).

  • We initialize i18next with these resources and configuration options.

Step 3: Create Translation Files

Create a Translations folder in your project directory if you haven’t already. Inside this folder, create two JSON files: en.json for English translations and ne.json for Nepali translations.

Translations/en.json

{
  "App": {
    "Language": {
      "English": "English",
      "Nepali": "Nepali"
    }
  }
}

Translations/ne.json

{
  "App": {
    "Language": {
      "English": "अंग्रेजी",
      "Nepali": "नेपाली"
    }
  }
}

We will need to add all of our translation into these two files.

Step 4: Create Language Switcher Component

Create a file named Language.js in your components directory.

import React from "react";
import i18n from "../../utils/I18n";
import { useTranslation } from "react-i18next";
import Session from "../../utils/Session";
import { SESSION_STORAGE_KEY as LanguageKey } from "../../utils/Language";
import LanguageView from "./Language-view";
import { DropdownMethodType } from "../Dropdown/Dropdown-container";

const Language: React.FC = () => {
  const { t } = useTranslation("App.Language");

  const changeLanguageToNepali = () => {
    i18n.changeLanguage("ne");
    Session.set(LanguageKey, { Language: "ne" });
  };

  const changeLanguageToEnglish = () => {
    i18n.changeLanguage("en");
    Session.set(LanguageKey, { Language: "en" });
  };

  const LANGUAGE_DROPDOWNS: DropdownMethodType[] = [
    {
      key: "English",
      label: t("English"),
      onClick: changeLanguageToEnglish,
    },
    {
      key: "Nepali",
      label: t("Nepali"),
      onClick: changeLanguageToNepali,
    },
  ];

  return (
    <Dropdown dropdownMethods={languageDropdowns} dropdownIcon={FiGlobe} />
  );
};

export default Language;

In this component:

  • We use the useTranslation hook to get the t function for translations.

  • We define functions to change the language to Nepali and English, respectively.

  • We create a dropdown configuration for language selection.

  • We import necessary modules and icons.

  • We define a functional component that accepts languageDropdowns as props and renders a Dropdown component.

I am using a build in Dropdown component. You can replace that with any other components.

The LANGUAGE_DROPDOWNS array contains objects that represent the language options. Each object has:

  • key: A unique key for the language.

  • label: The label to be displayed in the dropdown, fetched using the t function for translations.

  • onClick: A function that changes the language when the option is selected.

By following these steps, you have successfully set up internationalization in your React application using i18next. You now have a language switcher component that allows users to toggle between English and Nepali. This setup can be extended to include more languages and further customization based on your application's requirements.

In this example, the translation files en.json and ne.json contain the necessary translations for the language dropdown. The Language.js file handles the logic for switching languages. By using the t function from the useTranslation hook, the labels for the language options are dynamically translated based on the selected language.

Are you curious about what it’s like to navigate life as an international student in the USA? Or how to juggle a 9 to 5 job as a software engineer while pursuing your passion projects from 5 to 9? If so, join me on this thrilling journey as I share my experiences, challenges, and successes in real time.

In my newsletter, you’ll get an inside look at my life as I develop various products and work towards scaling my business. I’ll be transparent about the lessons I learn, the strategies I use, and the insights I gain along the way. From discovering startup ideas and launching them quickly to becoming profitable and preparing for interviews at top companies—I cover it all.

But this newsletter is more than just a glimpse into my life; it’s an invitation for you to learn, grow, and be inspired. Whether you’re an aspiring entrepreneur, a student, or someone who’s simply curious about bringing their own projects to life, you’ll find valuable advice, practical tips, and motivational stories that will help you on your own journey.

Read My Story and Explore My Projects

If you are interested in starting a newsletter like this, try out beehive for free

Reply

or to participate.