You are looking at internationalization! And one of the best rich libraries for this is i18next library for react! Simple to use! Good doc! This answer will be more then sufficient to get it well done!
https://react.i18next.com/
To note: (i18n => internationalization => i <18 chars> n)!
Getting started is a good place to start! The doc is well!
https://react.i18next.com/getting-started
For simple translations you use somethig like bellow:
<div>{t('simpleContent')}</div>
If no translation is provided the whatever was passed to t() method will be used! Otherwise you can provide translation files as much as you want!
For all languages! There is the fallback lang config too!
How to init and use example
import React from "react";
import ReactDOM from "react-dom";
import i18n from "i18next";
import { useTranslation, initReactI18next } from "react-i18next";
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.init({
// the translations
// (tip move them in a JSON file and import them,
// or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui)
resources: {
en: {
translation: {
"Welcome to React": "Welcome to React and react-i18next"
}
}
},
lng: "en", // if you're using a language detector, do not define the lng option
fallbackLng: "en",
interpolation: {
escapeValue: false
}
});
function App() {
const { t } = useTranslation();
return <h2>{t('Welcome to React')}</h2>;
}
// append app to dom
ReactDOM.render(
<App />,
document.getElementById("root")
);
You can see how to init!
And how translations are passed! In this case they are inline! Or directly passed! (see till the end! There is more options)
Production
For production different options are availables! Mainly have translation part of the react app (bundle)! Or on the server side! For a web app! Having them server side can be more suitable!
This page will give a strong overview:
https://react.i18next.com/guides/quick-start
Configure i18n
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
// the translations
// (tip move them in a JSON file and import them,
// or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui)
const resources = {
en: {
translation: {
"Welcome to React": "Welcome to React and react-i18next"
}
},
fr: {
translation: {
"Welcome to React": "Bienvenue à React et react-i18next"
}
}
};
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.init({
resources,
lng: "en", // language to use, more information here: https://www.i18next.com/overview/configuration-options#languages-namespaces-resources
// you can use the i18n.changeLanguage function to change the language manually: https://www.i18next.com/overview/api#changelanguage
// if you're using a language detector, do not define the lng option
interpolation: {
escapeValue: false // react already safes from xss
}
});
export default i18n;
Then you make sure to import it in the index.js (ts)! So init script execute! And i18next instance get created!
import React, { Component } from "react";
import ReactDOM from "react-dom";
import './i18n'; // <<<<<<<<--here
import App from './App';
// append app to dom
ReactDOM.render(
<App />,
document.getElementById("root")
);
A more complete config and options
https://react.i18next.com/latest/using-with-hooks
But before that install command:
npm install react-i18next i18next --save
// if you'd like to detect user language and load translation
npm install i18next-http-backend i18next-browser-languagedetector --save
Check the comments in the code bellow:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
// don't want to use this?
// have a look at the Quick start guide
// for passing in lng and translations on init
i18n
// load translation using http -> see /public/locales (i.e. https://github.com/i18next/react-i18next/tree/master/example/react/public/locales)
// learn more: https://github.com/i18next/i18next-http-backend
// want your translations to be loaded from a professional CDN? => https://github.com/locize/react-tutorial#step-2---use-the-locize-cdn
.use(Backend)
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
.use(LanguageDetector)
// pass the i18n instance to react-i18next.
.use(initReactI18next)
// init i18next
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
fallbackLng: 'en',
debug: true,
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
}
});
export default i18n;
You can see that there is a plugin that help with getting translation from the backend! Check the link here!
One too can make an ajax call! And get json response! That hold the exact translation then load it! you can check how in the section before the last!
Make sure to check the comments! And docs links! Check what each plugin do! the languageDetector! Is helpful!
Usage and translation
To translate your content ((usage)) (what you wanted above in the button:
useTranslation() hook!
import React from 'react';
// the hook
import { useTranslation } from 'react-i18next';
function MyComponent () {
const { t, i18n } = useTranslation();
return <h1>{t('Welcome to React')}</h1>
}
See the page for more options and details! Using HOC or Translation component! Also Trans component!
Well i'll include the examples:
import React from 'react';
// the hoc
import { withTranslation } from 'react-i18next';
function MyComponent ({ t }) {
return <h1>{t('Welcome to React')}</h1>
}
export default withTranslation()(MyComponent);
import React from 'react';
// the render prop
import { Translation } from 'react-i18next';
export default function MyComponent () {
return (
<Translation>
{
t => <h1>{t('Welcome to React')}</h1>
}
</Translation>
)
}
import React from 'react';
import { Trans } from 'react-i18next';
export default function MyComponent () {
return <Trans><H1>Welcome to React</H1></Trans>
}
// the translation in this case should be
"<0>Welcome to React</0>": "<0>Welcome to React and react-i18next</0>"
More details about trans here
Clearly the cooler way is the hook one!
Otherwise Trans is the way to go for translation with dom elements included (jsx)!
Translations and place
Two options! Have them in server side! Or part of the app bundle!
Server Side
For the server side it's pretty simple you can use the plugin already mentionned above! Check the link here!
Or even simply have an endpoint that serve translation files! And load them yourself! Make sure to load translations on demand! for the one specific lang! And at change! The plugin already allow all this!
Know that to dynamically load translation! You can use:
i18n.addResources() or i18n.addResourcesBundle()!
The second may be more suitable as it give deep and overite as extra options!
https://www.i18next.com/overview/api#addresource
And clearly! With a backend all go as json responses! Which automatically will be loaded as js objects!
To mention in server side! Translation are good to go in files! Both clean! And can be passed to no IT people to update them or add new languages translations.
Part of the app
Otherwise the other option! Is to have them part of the app! For web app you generally don't want to do that to keep the bundle small! But if you work on a desktop app like using electron! Then having it locally make sense!
A good way would be:
Generally you'll make an i18n folder
My config would be!
[![enter image description here][2]][2]
`index.js` is thge i18n module initializing and config file! The one already listed twice!
```ts
// ....
import translationEN from './locales/en/translation.json';
import translationFR from './locales/fr/translation.json';
import detector from 'i18next-browser-languagedetector'
// the translations
const resources = {
en: {
translation: translationEN
},
fr: {
translation: translationFR
}
};
// ....
I used json files here! And can have people Write the translations! Then just add them! And it's more organized!
One can use a js file instead of a json file too!
Change language
https://www.i18next.com/overview/api#changelanguage
import i18n exported instance!
i18n.changeLanguage('fr') // return promise
i18next library and instance!
Know that here we are using the i18n library as per
https://www.i18next.com/
And the react binding! (the init in config)
Know that you can use the i18next instance and all it's api! (import it from the config module! As we export it there!
Here go it's api!
https://www.i18next.com/overview/api
just in case! Generally you don't need to bother while in react! But you may! As for example dynamic loading of resources (translations) (not preloading)! As already mentioned!
Locize a gui managment tool and internationalization platform
https://react.i18next.com/guides/multiple-translation-files
Mentioned here!
You can both profit and check the multi translation! And too name spaces!
Otherwise for big projects! Locize may seems intersting!
And in big projects! Translations should always be separated!
In server side! You can always have the translations go in json files! And normal people can manage them! Like real hired translators!