Get current language next-i18next
20,582
Solution 1
withTranslation
injects the i18n
object.
import {withTranslation} from '../config/next-i18next';
const Home = function Home({ i18n }) {
return (<div>{i18n.language}</div>)
// ----------------^
};
Home.getInitialProps = async () => {
return {namespacesRequired: ['home']}
};
export default withTranslation('home')(Home);
Or using Hooks,
import {useTranslation} from '../config/next-i18next';
const Home = function Home() {
const { i18n } = useTranslation('home');
return (<div>{i18n.language}</div>)
// ----------------^
};
Home.getInitialProps = async () => {
return {namespacesRequired: ['home']}
};
export default Home;
Solution 2
With Next.js you could also use the useRouter hook.
import {withTranslation} from '../config/next-i18next';
import { useRouter } from 'next/router'
const Home = function Home() {
const router = useRouter()
const currentLang = router.locale // => locale string eg. "en"
return (<div>test</div>)
};
Home.getInitialProps = async () => {
return {namespacesRequired: ['home']}
};
export default withTranslation('home')(Home);
Author by
gdfgdfg
Updated on May 06, 2021Comments
-
gdfgdfg almost 3 years
I am using NextJS with next-i18next. This is my home page:
import {withTranslation} from '../config/next-i18next'; const Home = function Home() { return (<div>test</div>) }; Home.getInitialProps = async () => { return {namespacesRequired: ['home']} }; export default withTranslation('home')(Home);
What I want is to get current language inside a component/page, how can I do that ?