React i18 next
Project Structure
my-app/
├── public/
│ ├── index.html
│ └── locales/
│ ├── en/
│ │ └── translation.json
│ ├── de/
│ │ └── translation.json
│ └── ...
├── src/
│ ├── i18n.ts
│ ├── App.tsx
│ ├── index.tsx
│ └── components/
│ └── ExampleComponent.tsx
├── tsconfig.json
├── package.json
└── ...
Step-by-Step Setup
-
Install the necessary packages:
npm install i18next react-i18next i18next-http-backend i18next-browser-languagedetector
-
Create the translation files:
public/locales/en/translation.json
{
"welcome": "Welcome",
"description": "This is an example description."
}public/locales/de/translation.json
{
"welcome": "Willkommen",
"description": "Dies ist eine Beispielbeschreibung."
} -
Initialize i18next:
// src/i18n.ts
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import HttpBackend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
i18n
.use(HttpBackend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: 'en',
debug: true,
interpolation: {
escapeValue: false,
},
backend: {
loadPath: '/locales/{{lng}}/translation.json',
},
});
export default i18n; -
Provide i18next to your React app:
// src/index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { I18nextProvider } from 'react-i18next';
import App from './App';
import i18n from './i18n';
ReactDOM.render(
<I18nextProvider i18n={i18n}>
<App />
</I18nextProvider>,
document.getElementById('root')
); -
Use the
useTranslation
hook in your components:// src/components/ExampleComponent.tsx
import React from 'react';
import { useTranslation } from 'react-i18next';
const ExampleComponent: React.FC = () => {
const { t, i18n: { changeLanguage } } = useTranslation();
return (
<div>
<h1>{t('welcome')}</h1>
<p>{t('description')}</p>
<button onClick={() => changeLanguage('de')}>Deutsch</button>
<button onClick={() => changeLanguage('en')}>English</button>
</div>
);
};
export default ExampleComponent; -
Use the component in your app:
// src/App.tsx
import React from 'react';
import ExampleComponent from './components/ExampleComponent';
const App: React.FC = () => {
return (
<div>
<ExampleComponent />
</div>
);
};
export default App;
Summary
- Install
react-i18next
and dependencies. - Create translation JSON files in
public/locales
. - Initialize
i18next
insrc/i18n.ts
withHttpBackend
andLanguageDetector
. - Wrap your app with
I18nextProvider
. - Use the
useTranslation
hook in your components for translating text and changing languages.