Next.js Discord

Discord Forum

Shared layout can get child params?

Answered
Chartreux posted this in #help-forum
Open in Discord
ChartreuxOP
Imagine you have a structure like this:
app/
layout.tsx
profile/
[id]/
main/
page.tsx
detail/
page.tsx

Basically the layout will need to show different text between main and detail page, but they have same UI, so it make sense to share it but have different text.
Currently obvious way is to make each page has its own layout, but in this case I personally think the shared layout is way cleaner than layout duplication and change the content.
Is this possible?
Answered by Eric Burel
Craft a client component and get the pathName from there https://nextjs.org/docs/app/api-reference/functions/use-pathname
View full answer

7 Replies

Craft a client component and get the pathName from there https://nextjs.org/docs/app/api-reference/functions/use-pathname
Answer
ChartreuxOP
This is the only way for shared layouts, am I correct?
yes
Asari
What are the performance considerations by turning the layout into a client component? I'm in the middle of converting to app router right now and have been on this decision as well, whether to have groups and layouts that are very similar or having a client component that changes a few small things on one layout
@Asari What are the performance considerations by turning the layout into a client component? I'm in the middle of converting to app router right now and have been on this decision as well, whether to have groups and layouts that are very similar or having a client component that changes a few small things on one layout
function Layout({ children }) {
  return (
    <main>
      <nav>
        <NavLink href="/a">A</NavLink>
        <NavLink href="/b">B</NavLink>
        <NavLink href="/c">C</NavLink>
      </nav>
      {children}
    </main>
  )
}

"use client";
function NavLink({ href, children }) {
  const pathname = usePathname();
  const isActive = pathname === href;
  return (
    <a
      href={href}
      className={isActive ? activeClass : inactiveClass}
    >
      {children}
    </a>
  );
}

you don't have to make the entire layout client components. you can move the client components to the leaves of the component tree
Asari
Thank you @joulev , that's definitely the best direction to go 🙏
ChartreuxOP
Thanks! and agree with just use client for the one we need to!
My approach since I use MUI, active is on the parent nav but then,
in this case, solution I'm going to is just to wrap the nav to another component and use use client there only

function Layout({ children }) {
  return (
    <main>
      <MyNavigation>
      {children}
    </main>
  )
}