Reputation:
First I Initialize i18next inctance
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
const resources = {
en: {
translation: {
'Welcome to React': 'Welcome to React and react'
}
},
de: {
translation: {
'Welcome to React': 'Bienvenue à React et react-i18next'
}
}
};
i18n.use(initReactI18next).init({
resources,
lng: 'de',
interpolation: {
escapeValue: false
}
});
export default i18n;
and then I am using the instance with useTranslation hook in my component
import React from 'react'
import { useTranslation } from 'react-i18next'
import classes from './intro.module.scss'
export default function Intro() {
const { t, i18n } = useTranslation()
return (
<div className={classes.container}>
<div className={classes.innerContainer}>
<h1>{t('Welcome to React')}</h1>
</div>
</div>
)
}
so now how do I change the language to de from default language I initialized in i18n instance
I have a button on my navbar and I want that when I click on that button the languages should toggle.
Upvotes: 46
Views: 93010
Reputation: 307
Try this to see what language the user is using in their browser,
const getUserLanguage = () => window.navigator.userLanguage || window.navigator.language;
window.navigator.language
works for most of the modern browsers but to be on the safe side adding window.navigator.userLanguage
And this one to change the language, https://github.com/prajun7/react-till-now/blob/main/src/modules/I18n/index.ts#L1
You can play around here, https://prajun7.github.io/react-till-now/ Just change the language in the right side.
Upvotes: 0
Reputation: 101
In case anyone needs to get the current selected language, this is how you get it
const getLanguage = () => i18next.language || window.localStorage.i18nextLng
Upvotes: 10
Reputation:
Try this, pass the language inside the function to invoke different languages.
import React from 'react'
import { useTranslation } from 'react-i18next'
import classes from './intro.module.scss'
export default function Intro() {
const { t, i18n } = useTranslation()
const changeLanguageHandler = (lang) =>
{
i18n.changeLanguage("de")
}
return (
<div className={classes.container}>
<div className={classes.innerContainer}>
<h1>{t('Welcome to React')}</h1>
</div>
</div>
)
}
Upvotes: 69
Reputation: 653
You can find all the informations you need on the documentation of react-i18n: https://react.i18next.com/legacy-v9/step-by-step-guide#d-let-the-user-toggle-the-language
You need to use the function i18n.changeLanguage() and pass as props the language desired.
Upvotes: 5