Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current language next-i18next

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 ?

like image 639
gdfgdfg Avatar asked Jun 07 '20 08:06

gdfgdfg


2 Answers

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;
like image 198
felixmosh Avatar answered Oct 18 '22 01:10

felixmosh


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);
like image 36
PMarc Avatar answered Oct 18 '22 01:10

PMarc