Next.js Discord

Discord Forum

App Router Layout Help

Answered
Alaska pollock posted this in #help-forum
Open in Discord
Alaska pollockOP
Hey Everyone 👋

Looking for some help with setting up layouts with the new app router.

How do I conditionally hide the <MobileNav/> on certain routes. I essentially want the <MobileNav/> to appear on all routes apart from the intial page load (route="/"). Im using server components and having a nightmare trying to dynamically show this navigation bar. Not sure If Im just not implementing layout correctly.

Any help would be hugely appreciated.
Answered by Shy Albatross
to opt pages in and out of specific layouts, you can use route groups
View full answer

16 Replies

Shy Albatross
to opt pages in and out of specific layouts, you can use route groups
Answer
Shy Albatross
you would put the common stuff in the root layout, and at the line where you want to have 2 different sub-layouts, you create groups, like (withnav) and (nonav) or whatever, then put correspnding layouts and pages in those groups
what's red I'd put in root layout, then

(withnav) layout
<>
  <SiteHeader />
  <div>{children}</div>
</>

(nonav) layout
<div>{children}</div>
if you only want to hide the <MobileNav/> then I'd do a similar thing, but pass a prop to <SiteHeader /> and use that prop to conditionally render <MobileNav />, then you set that prop to true in one group layout and to false in the other group
so instead you would have something like

(withmobile) layout
<>
  <SiteHeader mobile={true} />
  <div>{children}</div>
</>


(nomobile) layout
<>
  <SiteHeader mobile={false} />
  <div>{children}</div>
</>
@Shy Albatross to opt pages in and out of specific layouts, you can use route groups
Alaska pollockOP
I appreciate your reply. Can you give me some more context on this. If I want to hide the <SiteHeader/> on these routes ["/", "login", "signup"] how would I do that with child layouts? Since my main layout.tsx has siteHeader in? Does that mean I need to add SiteHeader to all other layouts
Shy Albatross
one group with SiteHeader, one without, just like in my first message
you would create those 2 groups: (withnav) and (nonav) - those are folder names, and you'd put the pages in those groups, opting them into the layout you want
so main page, login and signup would go into the (nonav) folder
Alaska pollockOP
Like this?
Does that mean Id need another withoutNav folder and add everything in my /app directory into it. Results in every route having a /withoutNav url
Shy Albatross
(withnav) not withnav
read the docs from the link above
Alaska pollockOP
Woah I appreciate your help. This is one crazy pattern but got it working so thank you thank you