react-i18n-translation
is a lightweight React library designed for internationalization and translation management in React applications. It provides a simple and efficient way to handle multilingual content in React.js projects only.
- Easy integration with React.js.
- Lightweight and simple API.
- Dynamic language switching.
- Support for RTL (Right-to-Left) languages.
Install the library using npm or yarn:
npm install react-i18n-translation
# or
yarn add react-i18n-translation
Wrap your main.js file with the LangWrapper
to manage the language context:
import React from "react";
import ReactDOM from "react-dom/client";
import Cookies from 'js-cookie';
import { LangWrapper } from "react-i18n-translation";
import App from "./App";
const initialLang = Cookies.get('lang') || "en";
const dir = initialLang === "ar" ? "rtl" : "ltr";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<LangWrapper initialLang={initialLang} dir={dir}>
<App />
</LangWrapper>
);
A component that provides a dropdown for language selection. It automatically updates the language in the context.
import React, { useContext } from "react";
import { LangContext } from "react-i18n-translation";
const LanguageDropdown = () => {
const { lang, setLang } = useContext(LangContext);
const handleChange = (e) => {
setLang(e.target.value);
};
return (
<select value={lang} onChange={handleChange}>
<option value="en">English</option>
<option value="ar">Arabic</option>
<option value="de">German</option>
</select>
);
};
export default LanguageDropdown;
Fetch translations using the useTranslation
hook.
import React from "react";
import { useTranslation } from "react-i18n-translation";
import { langFiles } from "@/translation/langFiles";
const App = () => {
const { t } = useTranslation(langFiles);
return (
<div>
<LanguageDropdown />
<h1>{t("welcome")}</h1>
<p>{t("goodbye")}</p>
</div>
);
};
export default App;
Create JSON files for each language. For example:
{
"welcome": "Welcome",
"goodbye": "Goodbye"
}
{
"welcome": "أهلا بك",
"goodbye": "مع السلامة"
}
import en from "../translation/en.json";
import ar from "../translation/ar.json";
export const langFiles = { en, ar };
Include these files in your project and pass them to langFiles
in LangProvider
.
Wraps the application and provides language context.
Prop | Type | Default | Description |
---|---|---|---|
initialLang |
string | "en" |
Initial language to set. |
A hook to fetch translations.
Function | Description |
---|---|
t(key) |
Returns the translated string for the key. |
Ensure your project has the following dependencies installed:
react
(v17.0.0 or later)react-dom
(v17.0.0 or later)
Contributions are welcome! If you find a bug or have a feature request, feel free to create an issue or submit a pull request.
This project is licensed under the ISC License.
RTS_Dev