react-i18next icon indicating copy to clipboard operation
react-i18next copied to clipboard

Text content did not match & Error while hydrating

Open mtiganik opened this issue 2 years ago • 5 comments

🐛 Bug Report

A clear and concise description of what the bug is.

To Reproduce

A minimal reproducible example. A codesandbox <- I'm new to codesandbox - there are more errors over there

I'm following official Step-by-Step guide to include react-i18next to my next.js React project. I start it with default next app configuration:

npx create-next-app@latest
√  project name ... translation3
√  use TypeScript? ... Yes
√  use ESLint? ... No 
√  use Tailwind CSS? ... No 
√  use `src/` directory? ...  Yes
√  use App Router? (recommended) ...  Yes
√  default import alias (@/*)? ... No 

Then installed all required packages:

npm install i18next react-i18next i18next-http-backend i18next-browser-languagedetector next-i18next

Continuing with tutorial. I created i18n.ts file beside page.tsx, This file is exactly the same:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
// don't want to use this?
// have a look at the Quick start guide 
// for passing in lng and translations on init

i18n
  // load translation using http -> see /public/locales (i.e. https://github.com/i18next/react-i18next/tree/master/example/react/public/locales)
  // learn more: https://github.com/i18next/i18next-http-backend
  // want your translations to be loaded from a professional CDN? => https://github.com/locize/react-tutorial#step-2---use-the-locize-cdn
  .use(Backend)
  // detect user language
  // learn more: https://github.com/i18next/i18next-browser-languageDetector
  .use(LanguageDetector)
  // pass the i18n instance to react-i18next.
  .use(initReactI18next)
  // init i18next
  // for all options read: https://www.i18next.com/overview/configuration-options
  .init({
    fallbackLng: 'en',
    debug: true,

    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    }
  });

export default i18n;

to public folder I created locales folder which contains 3 language code whit json files, also populated them with required translations:

public
-locales
--en
---translation.json
--et
---translation.json
--ru
---translation.json

Example of a translation file:

// public/locales/en/translation.json
{
  "form": {
    "header": "Enter new form",
    "inputLabelText":"Enter num 1 or 2",
    "placeholderText":"1 or 2",
    "succesMessage": "Correct value",
    "errorMessage" : "Incorrect value"
  },
  "common":{
    "submitBtnText" : "Submit"
  }
}

In my next.js app, I removed globals.css and everything unnecessary from layout.tsx and from page.tsx. imported newly created"./i18n"to page.tsx and added Suspense:

"use client"
import "./i18n"
import Form from "./form";
import { Suspense } from "react";

export default function Home() {
  return (
    <Suspense fallback="loading">
      <main >
        <div >
          <Form />
        </div>
      </main>
    </Suspense>
  );
}

Then to display translations and change them I added custom React component Form:

"use client"
import React, { useState } from "react"
import { useTranslation } from "react-i18next";
// For debugging tried next-i18next useTranslation, but this one does not work either
// import { useTranslation } from "next-i18next"; 

export default function Form(){
  const [inputVal, setInputVal] = useState<string>("")
  const [error, setError] = useState("")
  const [succes, setSucces] = useState("")
  const {t, i18n} = useTranslation();

  const handleSubmit = () =>{
    setError("")
    setSucces("")
    if(inputVal == "1" || inputVal == "2"){
      setSucces(t("form.succesMessage"))
    }else {
      setError(t("form.errorMessage"))
    }
  }
  const handleLangChange= (lang:string) =>{
    i18n.changeLanguage(lang)
  }

  return(
    <>
    <h1>{t("form.header")}</h1>
    <label htmlFor="formVal">{t("form.inputLabelText")}: </label>
    <input type="text" id="formVal" placeholder={t("form.placeholderText")} 
    value={inputVal} onChange={(t) => {setInputVal(t.target.value)}}></input>
    <br></br>
    <button type="button" onClick={handleSubmit}>{t("common.submitBtnText")}</button>
    <span style={{color:"red"}}>{error}</span>
    <span style={{color:"green"}}>{succes}</span>
    <div className="dropdown">
<ul>
  <li onClick={()=> handleLangChange("en")}>English</li>
  <li onClick={()=> handleLangChange("et")}>Estonian</li>
  <li onClick={()=> handleLangChange("ru")}>Russian</li>
</ul>
</div>
    </>
  )
}

Expected behavior

Now when I run this with npm run dev Language switching works, but refreshing page gives error: langchange works error text content does not match hydration error

Why did those errors came if I refresh the page?

Your Environment

  • runtime version: i.e. node v20.12.1, browser Chrome 124.0.6367.119
  • i18next version: i.e. "^23.11.3"
  • os: Windows
  • any other relevant information

mtiganik avatar May 07 '24 11:05 mtiganik

You are using Next.js with the app router approach... you need to follow this guide: https://locize.com/blog/next-app-dir-i18n/

adrai avatar May 07 '24 11:05 adrai

Is there also some Typescript version for this app router guide? Even for page files I need to add PageProps for it to work:

// src/app/[lng]/page.tsx
import Link from 'next/link'

interface PageProps{
  params:{
    lng: string
  }
}

export default function Page({ params: {lng}}: PageProps) {
  return (
    <>
      <h1>Hi there!</h1>
      <Link href={`/${lng}/second-page`}>
        second page
      </Link>
    </>
  )
}

Conversion of all those files would be challenging

mtiganik avatar May 07 '24 12:05 mtiganik

image

https://github.com/i18next/next-app-dir-i18next-example-ts

adrai avatar May 07 '24 12:05 adrai

Hey @mtiganik I'm facing this issue with Next 12 + React 18... any leads on fixing this?

hawkeyes21 avatar Dec 04 '24 07:12 hawkeyes21

No... Haven't checked it for ages.

mtiganik avatar Dec 04 '24 09:12 mtiganik