40

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 ?

gdfgdfg
  • 3,181
  • 7
  • 37
  • 83

2 Answers2

52

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;
felixmosh
  • 32,615
  • 9
  • 69
  • 88
11

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);
PMarc
  • 119
  • 1
  • 2
  • It works only if you enable it modifying the next.config.js. You can enable max 100 "known" locales (I wanted to support any possible locale and I set it within 550 locales but it raise an error explaining there is this limit). Also it changes your url to go always on a path within a locale, mysite.com/mypage/ -> mysite.com/en-US/mypage , a behaviour that maybe you don't want. – Alex 75 Jan 25 '22 at 22:03
  • Thanks for the idea, @PMarc Could you please share your code of `withTranslation` function? It's not working from the box. – nlavr Jan 21 '23 at 12:59