learn react ui logoLearnReactUI
How to Build Multi Language Support with React

How to Build Multi Language Support with React

This is a simple React application demonstrating internationalization (i18n) using react-i18next.

[Demo]

Features

  • Supports multiple languages (English and Turkish).
  • Dynamically switches the language at runtime.
  • Organized and extensible translation resources.

Initialize i18n

The i18n.js file contains the initialization logic for i18next.
Translation resources are defined for en (English) and tr (Turkish).

Example snippet:

Initialize i18n

The i18n.js file contains the initialization logic for i18next.
Translation resources are defined for en (English) and tr (Turkish).

Example snippet:

const resources = {
  en: {
    translation: {
      welcome: "Welcome to our website!",
      about: "About Us",
      contact: "Contact Us",
      "change-language": "Change Language",
    },
  },
  tr: {
    translation: {
      welcome: "Web sitemize hoşgeldiniz!",
      about: "Hakkımızda",
      contact: "İletişim",
      "change-language": "Dili Değiştir",
    },
  },
};

i18n.use(initReactI18next).init({
  resources,
  lng: "en", // Default language
  interpolation: {
    escapeValue: false, // React already handles escaping
  },
});

export default i18n;

Use Translations in Components

The I18nSample.jsx file demonstrates how to use translations in a React component.

Example usage:

import React from "react";
import { useTranslation } from "react-i18next";

const I18nSample = () => {
  const { t, i18n } = useTranslation();

  const changeLanguage = (lng) => {
    i18n.changeLanguage(lng);
  };

  return (
    <div>
      <h1>{t("welcome")}</h1>
      <button onClick={() => changeLanguage("en")}>English</button>
      <button onClick={() => changeLanguage("tr")}>Türkçe</button>
    </div>
  );
};

export default I18nSample;

Adding More Languages

To add more languages:

  1. Update the resources object in i18n.js with the new language translations.
  2. Ensure the lng property matches the key in the resources object.

For example:

es: {
  translation: {
    welcome: '¡Bienvenido a nuestro sitio web!',
    about: 'Sobre Nosotros',
    contact: 'Contáctenos',
    'change-language': 'Cambiar idioma',
  },
},