I have TypeError on using the layout.tsx from next-intl doc on client-side

138 Views Asked by At

I have this code layout.tsx here from next-intl doc

import {NextIntlClientProvider} from 'next-intl';
import {notFound} from 'next/navigation';
 
export function generateStaticParams() {
  return [{locale: 'en'}, {locale: 'de'}];
}
 
export default async function LocaleLayout({children, params: {locale}}) {
  let messages;
  try {
    messages = (await import(`../../messages/${locale}.json`)).default;
  } catch (error) {
    notFound();
  }
 
  return (
    <html lang={locale}>
      <body>
        <NextIntlClientProvider locale={locale} messages={messages}>
          {children}
        </NextIntlClientProvider>
      </body>
    </html>
  );
}

When npm run dev, I have this error: Unhandled Runtime Error TypeError: Cannot destructure property 'children' of 'param' as it is undefined.

I have tried to using interface but the error still there.

interface Props {
  children?: React.ReactNode;
  params?: {
    locale: any;
  };
}
export default async function LocaleLayout({
  children,
  params: { locale },
}: Props)
1

There are 1 best solutions below

0
On
export default async function LocaleLayout({children, params: {locale}}) 

Here your component expect params as props to destruct locale from it but here

interface Props {
  children?: React.ReactNode;
  params?: {
    locale: any;
  };
}

you see that params is optional so if you don't pass it as props, the function cannot destruct locale from it

you can do this :

export default async function LocaleLayout({ children, params = {} }: Props) {
  const { locale } = params;
  //..
}

here params take {} as value if it is not provided this will solve the error, then, you destruct local from it.