m2v
m2v

Reputation: 673

react-i18next:: You will need to pass in an i18next instance by using initReactI18next

react-i18next:: You will need to pass in an i18next instance by using initReactI18next

I recently added the package and got this error. I have followed all the steps as far as I know.

I use Next.js with the next-i18next package which usually initialises itself automatically.

https://github.com/m2vi/downloader

Upvotes: 67

Views: 112908

Answers (13)

SgtPooki
SgtPooki

Reputation: 11669

I get that this post is talking about nextjs, so many of the answers here talk about server side rendering. I'm doing no such thing in my project, but this is a very popular answer so I figured i'd post my situation.

I am building a react component library with vite, typescript, react, and react-i18n. The problem I ran into here was that I was not marking react-i18next as external. By adding the following code, using my component library in the consuming website was no longer generating the error:

// vite.config.ts

...
  rollupOptions: {
    // ...,
    external: [
        'react',
        'react-dom',
        'react-18next'
    ],
    // ...,

Upvotes: 0

Ali Onar
Ali Onar

Reputation: 11

Nextjs App Router

// layout.tsx

import i18nConfig from '@/i18nConfig';
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { ReactNode } from 'react';
import { dir } from 'i18next';
import TranslationsProvider from '@/components/i18n/TranslationProvider';

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "Ali Onar",
  description: "Ali Onar - Software Engineer",
};

export function generateStaticParams() {
  return i18nConfig.locales.map(locale => ({ locale }));
}

const i18nNamespaces = ['common'];

export default function RootLayout({
  children,
  params: { locale }
}: {
  children: ReactNode;
  params: { locale: string };
}) {
  return (
    <html lang={locale} dir={dir(locale)}>
      <body className={inter.className}>
      <TranslationsProvider locale={locale} namespaces={i18nNamespaces}>
        {children}
      </TranslationsProvider>
        </body>
    </html>
  );
}

Check this repo for more

Upvotes: 0

tlanhan
tlanhan

Reputation: 1

Update: It only useful in server component. I dont think it's useful

I resolved this question by another way.

Next 13, router in app/ file

When I use getServerSideProps function,I met question NextJS. How to fix: "getServerSideProps" is not supported in app/

After search, I find a resolve how to render async page components as a child in next.js?

So, I add

import {use} from "react";
const { t } = use(useTranslation());

I got translation text.

Oh, I forget say my i18n config from next-app-dir-i18n

Upvotes: 0

Yasmin Lopes
Yasmin Lopes

Reputation: 11

I've been facing the same problem.

In my case, I solved by adding the I18nextProvider Wrapper


import { I18nextProvider } from 'react-i18next';
import i18n from './i18n';

type Props = {
  children: React.ReactNode;
};

export default function LocalizationProvider({ children }: Props) {
  const { currentLang } = useLocales();

  return (
    <I18nextProvider i18n={i18n}>
      <MuiLocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={currentLang.adapterLocale}>
        {children}
      </MuiLocalizationProvider>
    </I18nextProvider>
  );
}

Upvotes: 1

Seyed Morteza Mousavi
Seyed Morteza Mousavi

Reputation: 6963

If you face this error in react and jest, maybe this one can help you:

    jest.mock('react-i18next', () => ({
    // this mock makes sure any components using the translate hook can use it without a warning being shown
    useTranslation: () => {
        return {
            t: (str: string) => str,
            i18n: {
                changeLanguage: () => new Promise(() => {}),
            },
        }
    },
    initReactI18next: {
        type: '3rdParty',
        init: () => {},
    },
}))

as suggested in official doc.

Upvotes: 0

Sam Levine
Sam Levine

Reputation: 128

Be sure to import the i18n into the root of your app. This will resolve the error message and allow the translations to work properly.

This is outlined in the docs: https://react.i18next.com/latest/using-with-hooks#:~:text=Then%20import%20that%20in%20index.js%3A

P.S. If clicking the link doesn't bring you to the exact location, search in the document (ctr + f): "Then import that in index.js"

Upvotes: 1

Jordan
Jordan

Reputation: 1

Had the same issue, problem was that I wasn't importing the i18n.js file in app.js. Check and make sure you are importing this file correctly in your app.

Upvotes: 0

Sohaib El Mediouni
Sohaib El Mediouni

Reputation: 195

Try this : in your next-i18next.config.js:

    const path = require('path')
module.exports = {
    i18n: {
        defaultLocale: 'fr',
        locales: ['en', 'fr'],
        localePath: path.resolve('./public/locales')
    },
};

and in your _app.js try to pass the config file as a sencond param like this :

import { appWithTranslation } from 'next-i18next'
import nextI18NextConfig from '../../next-i18next.config'
....
export default appWithTranslation(MyApp, nextI18NextConfig); 

N.B if you are using Next.js's dynamic import feature to load a module only on the client side disable it otherwise it will not work

export default dynamic(() => Promise.resolve(index), { ssr: false }); //to be removed

Upvotes: 2

pa4080
pa4080

Reputation: 951

In my case the problem was a silly typo caused by the VSC import suggestions and at first place my carelessness.

So instead of:

import { useTranslation } from "next-i18next";

... the import statement was:

import { useTranslation } from "react-i18next";

Upvotes: 27

mihca
mihca

Reputation: 1257

This error message may be shown although it is not the root cause of the problem.

I had the following build error message:

react-i18next:: You will need to pass in an i18next instance by using initReactI18next
TypeError: Cannot read properties of undefined (reading 'split')
    at LanguageSwitcherLink ...

The root cause here was the TypeError.

In my case, the TypeError occurred because I had components with parameters in pages directory. Thus, during next build these components were attempted to be build as static pages. This failed because expected parameters were missing, which is why they were undefined.

Solution for me: move components outside of pages folder. Afterwards, there is also no error message anymore with respect to initReactI18next.

Upvotes: 0

Serafim
Serafim

Reputation: 483

I had this issue too.

But I had "revalidate" property in getStaticProps. When I removed it, the error went away.

P.S. Maybe this will help someone

Upvotes: -1

Aayush Bhattacharya
Aayush Bhattacharya

Reputation: 1934

update next-i18next.config.js

module.exports = {
    i18n: {
        defaultLocale: 'en',
        locales: ['en', 'de', 'fr'],
    },
    react: { useSuspense: false },//this line
};

Upvotes: 9

juliomalves
juliomalves

Reputation: 50368

From the next-i18next docs:

Then we add serverSideTranslation to getStaticProps or getServerSideProps (depending on your case) in our page-level components.

Meaning you'll need to add serverSideTranslation to the pages that need translations.


For example in your pages/d/[tab]/index file:

import Head from 'next/head';
import { Input } from '../../../components/Input';
import YouTube from '../../../components/youtube/Main';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';

const index = () => {
    return (
        <>
            <Head>
                <title>YouTube</title>
            </Head>
            <YouTube />
        </>
    );
};

export const getServerSideProps = async ({ locale }) => ({
    props: {
        ...(await serverSideTranslations(locale, ['common']))
    }
});

export default index;

Then further down in your Main component you can access the documentation translation using:

t('pages.documentation')

Upvotes: 30

Related Questions