This is a simple example of how to use i18next with React to translate your application
Note:
i18next
is a powerful internationalization framework for JavaScript that provides a complete solution to localize and translate your productNote: We are using
Vite
to build this project, but you can useNext.js
or any other bundler
- Clone this repository
- Install the dependencies with
npm install
- Run the project
npm run dev
- Create a new file called
translation.json
inside its respective language folder (e.g.en
for English) and put it inside thesrc/locales
folder
{
"welcome": "Hello World"
}
- Add the new language to the
i18n.ts
file
// Other code here...
// Import the new language
import en from './locales/en/translation.json'
// Add the new language to the resources object
const resources = {
en: {
translation: en,
},
// Other languages here...
}
- Add the translation in your React components:
import './i18n.ts' // * Import the i18n configuration
import { useTranslation } from 'react-i18next'
export default function App() {
// * Use the t() function to translate text, and the i18n object to change the language
const { t, i18n } = useTranslation()
return (
<>
<h1>{t('welcome')}</h1>
<button onClick={() => i18n.changeLanguage('en')}>English</button>
</>
)
}