M.Çelik
M.Çelik

Reputation: 15

Next.js error: Text content did not match

I am using react-i18next in my next.js project for localization. But I take these errors when I refresh the page.

Errors

  1. Warning: Text content did not match. Server: "page_about" Client: "About Us"
  2. Warning: An error occurred during hydration. The server HTML was replaced with client content in <div>.
  3. Uncaught Error: Text content does not match server-rendered HTML.
  4. Uncaught Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.

src/configs/i18n.js

import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import Backend from 'i18next-http-backend'
import LanguageDetector from 'i18next-browser-languagedetector'

i18n
  // Enables the i18next backend
  .use(Backend)

  // Enable automatic language detection
  .use(LanguageDetector)

  // Enables the hook initialization module
  .use(initReactI18next)
  .init({
    lng: 'tr',
    backend: {
      /* translation file path */
      loadPath: '/locales/{{lng}}.json'
    },
    fallbackLng: 'tr',
    debug: false,
    keySeparator: false,
    react: {
      useSuspense: false
    },
    interpolation: {
      escapeValue: false,
      formatSeparator: ','
    }
  })

export default i18n

_app.js

...
import 'src/configs/i18n'

const MyApp = ({ Component, pageProps }) => {

    const getLayout = Component.layout ?? (page => <Layout>{page}</Layout>)

    return (
        <>
            <Provider store={store}>
                <ThemeProvider theme={theme}>
                    {
                        getLayout(<Component {...pageProps} />)
                    }
                </ThemeProvider>
            </Provider>
        </>
    )
}

MyApp.getInitialProps = async (context) => {
    const ctx = await App.getInitialProps(context)

    return {
        ...ctx,
    };
};


export default MyApp

Translations.js

import { useTranslation } from "react-i18next";

const Translations = ({ text }) => {
  // ** Hook
  const { t } = useTranslation()

  return <>
    {`${t(text)}`}
  </>
}

export default Translations

I use in a component

...
<Translations text={subItem.name} />
...

I tried to use next-i18next, Suspense, namespaces

Upvotes: 0

Views: 500

Answers (1)

Rao Asim
Rao Asim

Reputation: 330

you have to pass serverSideTranslation function to your page component in order for it to access the transalation file like this :

import { serverSideTranslations } from "next-i18next/serverSideTranslations";

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

Upvotes: 0

Related Questions