QuiiBz / next-international

Type-safe internationalization (i18n) for Next.js
https://next-international.vercel.app
MIT License
1.26k stars 59 forks source link

How to use useI18n() in the client component? #192

Closed trlanfeng closed 11 months ago

trlanfeng commented 11 months ago

How to use useI18n in a client-side component? Just like in the example examples/next-app/app/[locale]/switch.tsx, but I want to add a "Switch Language" text that is obtained from a language file. However, when using useI18n in a client-side component, it prompts that it needs to be included in I18nProviderClient.

'use client';

import { useChangeLocale,useI18n } from '../../locales/client';

export function Switch() {
  const t = useI18n();
  const changeLocale = useChangeLocale();

  return (
    <>
      <label>{t('switch-language')}</label>
      <button type="button" onClick={() => changeLocale('en')}>
        EN
      </button>
      <button type="button" onClick={() => changeLocale('fr')}>
        FR
      </button>
    </>
  );
}
gustaveWPM commented 11 months ago

it prompts that it needs to be included in I18nProviderClient.

Yes.

src/app/[locale]/layout.tsx


'use client';

// * ...

export default function RootLayout({ children }: LayoutMinimalProps) { return (

{children}

); }



This doesn't seem to be a _bug_, but more a _question_, though.
QuiiBz commented 11 months ago

You have to wrap your client components in I18nProviderClient. The easiest option is to do so in a layout: https://next-international.vercel.app/docs/app-setup#move-your-existing-files