Next.js Discord

Discord Forum

Send parameter from page to layout using App Directory

Unanswered
Mourning Warbler posted this in #help-forum
Open in Discord
Mourning WarblerOP
Hi guys,



I am a kind of lost. How can I send parameter from page.tsx to layout.tsx using the last version of Next.JS? I already tried to apply different solutions without success. I need to apply a custom data attribute to <html> tag that is the "id of page". So, I need to pass this attribute from each page of the project.

2 Replies

Shy Albatross
You could useSelectedLayoutSegments in the root layout, where <html> exists and evalutae the segments to produce your secret attribute. But that would mean making your root layout a client component. Maybe parsing the URL is a valid approach, depending on your use case (depends on which pages are to modify that attr - is it tied to pages, or rather route segments?)
// app/layout.tsx
export default function Layout({ children }) {
  return <LayoutClient>{children}</LayoutClient>;
}

// app/layout.client.tsx
export default function LayoutClient({ children }) {
  const pathname = usePathname();
  return (
    <html data-pathname={pathname}>
      <body>{children}</body>
    </html>
  );
}