i18nexus / next-i18n-router

Next.js App Router internationalized routing and locale detection.
MIT License
262 stars 18 forks source link

Use translations in a component outside of the translation wrapper? #93

Closed veryloooong closed 2 months ago

veryloooong commented 2 months ago

Hello, I would like to request help regarding translating my current app. Currently, I have a fixed header and a footer in my layout.tsx file:

export default function RootLayout({
  children,
  params,
}: {
  children: React.ReactNode
  params: { locale: string }
}) {
  return (
    <html lang={params.locale}>
      <body>
        <Header />
        <main>
          {children}
        </main>
        <Footer />
      </body>
    </html>
  )
}

With the main element containing my main page, which is successfully translated for both server and client components when I follow instructions on the website:

export default async function Home({ params }: { params: { locale: string } }) {
  const { t, resources } = await initTranslations(params.locale, i18nNamespaces);

  return (
    <TranslationsProvider
      namespaces={i18nNamespaces}
      locale={params.locale}
      resources={resources}>
        {/* ... */}
    </TranslationsProvider>
  )
}

But I would also want to translate the <Header /> and <Footer /> components in the layout. I want to keep them there for consistency. But they are not wrapped in the <TranslationsProvider /> so they aren't translated. The header is a client component and the footer is a server component. So I would like to ask for a guide on this. I have searched but haven't found a good answer. Thank you in advance.

i18nexus commented 2 months ago

If your Header is a client component, it should be able to access translations via the useTranslations hook. For all nested server components, you will need to use initTranslations again.