Guide: How to Set Up i18n for Multi-Language Support in React Applications
1. Create i18n.js
File
- In your
src
folder, create a file namedi18n.js
. - Install Dependencies:
npm install i18next react-i18next i18next-browser-languagedetector i18next-http-backend
- Copy and paste the following code:
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import Backend from "i18next-http-backend";
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: "en",
debug: false,
interpolation: {
escapeValue: false,
},
backend: {
loadPath: "/locales/{{lng}}/translation.json",
},
detection: {
order: [
"querystring",
"cookie",
"localStorage",
"navigator",
"htmlTag",
"path",
"subdomain",
],
lookupQuerystring: "lng",
lookupCookie: "i18next",
lookupLocalStorage: "i18nextLng",
caches: ["localStorage", "cookie"],
excludeCacheFor: ["cimode"],
checkWhitelist: true,
lookupFromPathIndex: 0,
lookupFromSubdomainIndex: 0,
},
supportedLngs: ["en", "ar"],
nonExplicitSupportedLngs: true,
load: "languageOnly",
});
export default i18n;
2. Set Up Translation Files
- Create a folder structure in the
public
directory:public/locales/en/translation.json
andpublic/locales/ar/translation.json
. - Fill each file with translations:
public/locales/ar/translation.json
:
{
"welcome": "السلام عليكم ورحمة الله وبركاته"
}
public/locales/en/translation.json
:
{
"welcome": "Welcome to our website!"
}
3. Initialize i18n in Your Project
In your main.jsx
, import the i18n.js
file to initialize it:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import "./i18n"; // Import i18n configuration
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
);
4. Implement useTranslation
in a Component
In any component, use the useTranslation
hook to access translation functionality:
import React from "react";
import { useTranslation } from "react-i18next";
const App = () => {
const { t, i18n } = useTranslation();
const changeLanguage = (lng) => {
i18n.changeLanguage(lng);
};
return (
<div>
<p>{t('welcome')}</p>
{/* Using {t('key')} is the standard approach in i18n to make components language-agnostic and responsive to user language settings, basically you wont include the actual text in your components. */}
<button onClick={() => changeLanguage('en')}>English</button>
<button onClick={() => changeLanguage('ar')}>Arabic</button>
</div>
);
};
export default App;
5. Test Dynamic Language Switching
- Run your application.
- Ensure the language switches when clicking the "English" or "Arabic" buttons.
- Verify the language setting persists (due to
localStorage
andcookies
).