Localization in React Js using i18next library
- Get link
- X
- Other Apps
Localization in React Js using i18next library
First, install the required packages:
npm install i18next react-i18next --save
i18n.js
file that initializes i18next:In this file, we're initializing i18next with two languages (English and French) and a single translation string (greeting). The initReactI18next
function initializes the react-i18next library.
Next, in your React component, you can use the useTranslation
hook to access translations:
import React from 'react'; import { useTranslation } from 'react-i18next'; function Greeting({ name }) { const { t } = useTranslation(); return <div>{t('greeting', { name })}</div>; } export default Greeting;
In this example, we're using the useTranslation
hook to get the t
function, which we can use to access translations. We're passing in the name
prop to the t
function to interpolate the name into the translated string.
Finally, in your app, you can wrap your top-level component with the I18nextProvider
to make the translations available to all components:
import React from 'react'; import ReactDOM from 'react-dom'; import { I18nextProvider } from 'react-i18next'; import i18n from './i18n'; import Greeting from './Greeting'; ReactDOM.render( <I18nextProvider i18n={i18n}> <Greeting name="Alice" /> </I18nextProvider>, document.getElementById('root') );
Greeting
component with the I18nextProvider
and passing in the i18n
instance we created earlier.- Get link
- X
- Other Apps
Comments