I recently learned about the implementation of internationalization in react app. Let me tell you the process.
There is a lot of libraries to help you implement i18n in React.js but I used i18next for the task.
Installation:
npm install i18next react-i18next i18next-browser-languagedetector
Let's install a few packages to make it work. Like i18next, react-i18next, and i18next-browser-languagedetector.
Just run the snippet in the terminal.
Then create a file named "i18n.js" or whatever you have chosen to, then add the following code:
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import English from "./en/translations";
import Bangla from "./bn/translations";
i18n
.use(LanguageDetector)
.use(initReactI18next)
.init({
// we init with resources
resources: {
English: English,
Bangla: Bangla,
},
fallbackLng: "English",
debug: true,
// have a common namespace used around the full app
ns: ["translations"],
defaultNS: "translations",
keySeparator: false, // we use content as keys
interpolation: {
escapeValue: false,
},
});
export default i18n;
I know there is no such file called English in the "./en/translations" folder, and we will create that later. But for now, let's move on to the next step.
In the index.js file add the following line.
import "./i18n";
By this translations are now globally accessible.
Now let's create the translations,
First, create folders and files in the following structure:
and add translations,
In en/translations.js
const English = {
translations: {
"NAME": "Akhlak Hossain Jim",
...
},
};
export default English;
And in bn/translations.js
const Bangla = {
translations: {
"NAME": "আখলাক হোসেন জিম",
...
},
};
export default Bangla;
In this way, you can set as many keys and values with short names and strings.
And it's now time for using it. Let's go to the App.js file or wherever you want to use, and use as follows:
import { useTranslation } from "react-i18next";
export default function App() {
const { t } = useTranslation();
return (
<div>{t("NAME")}</div>
);
}
And now it's all set.
These are the basic steps for adding i18next.
Top comments (0)