Introduction to i18next
i18next is an internationalization framework for JavaScript applications. It provides a robust solution for managing translation and localization needs. In this article, we will explore various APIs offered by i18next and share code examples to illustrate their usage.
Initialization
The first step to using i18next is to initialize it.
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
i18n
.use(initReactI18next)
.init({
resources: {
en: {
translation: {
"welcome": "Welcome to React and react-i18next",
}
},
de: {
translation: {
"welcome": "Willkommen bei React und react-i18next",
}
}
},
lng: "en",
fallbackLng: "en",
interpolation: {
escapeValue: false
}
});
Changing Languages
You can change the language programmatically using the changeLanguage
API.
i18n.changeLanguage('de');
Trans Component
The Trans
component from react-i18next is used for easily translating strings in React components.
import { Trans } from 'react-i18next';
function App() {
return (
<div>
<Trans i18nKey="welcome" />
</div>
);
}
useTranslation Hook
The useTranslation
hook provides translation functionality within functional components.
import React from 'react';
import { useTranslation } from 'react-i18next';
function App() {
const { t } = useTranslation();
return (
<div>
{t('welcome')}
</div>
);
}
Example Application
Below is a simple example of a React application using the above APIs.
import React from 'react';
import ReactDOM from 'react-dom';
import { useTranslation } from 'react-i18next';
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
i18n
.use(initReactI18next)
.init({
resources: {
en: {
translation: {
"welcome": "Welcome to React and react-i18next",
"thanks": "Thank you for using our application"
}
},
de: {
translation: {
"welcome": "Willkommen bei React und react-i18next",
"thanks": "Danke, dass Sie unsere Anwendung verwenden"
}
}
},
lng: "en",
fallbackLng: "en",
interpolation: {
escapeValue: false
}
});
function App() {
const { t } = useTranslation();
return (
<div>
<h1>{t('welcome')}</h1>
<p>{t('thanks')}</p>
<button onClick={() => i18n.changeLanguage('de')}>Change Language to German</button>
<button onClick={() => i18n.changeLanguage('en')}>Change Language to English</button>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
Through this simple example, you can see how powerful and easy it is to work with i18next for translating your application.
Hash: de5bae745685273290e1917241dc4c8bc3d70b2cf978ba1a1a3abc7ea5fda82b