I’m trying to build a NextJS (APP ROUTING) web application with 2 sections:
- Website
- Account
I would like users to access the restricted account section via domain.tld/account whereas the website lives in domain.tld
ISSUE:
There is a navbar component declared in the root layout as follows:
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className={poppins.className}>
<Navbar />
{children}
</body>
</html>
);
}
All page components in the app dir are sharing the above layout.
And here is my /account page component:
export default async function Account() {
return (
<>
<p>My Account</p>
</>
);
}
This returns the web navbar component which I do not want in the account section.
How can I separate the root layout as web and have a different child layout for account or admin?
2
Answers
There are two ways to display your navbar for all paths but the
/account
route and its children. Picking the right one depends on the rest of your structure.Generally speaking you can remove the
<Navbar />
from the root layout and place it in say/foo/layout.tsx
instead to make sure only/foo
and all child routes show the navbar while/account
does not.Otherwise, especially when it’s a distinction at root level, you have to use so called route groups which are a logical separation of folders and paths that does not affect routing directly. Route groups are denoted by folders whose names look like
(groupname)
. In your case you’d declare the following structure:In this example you’d still have a root layout at
app/layout.tsx
that defines the root layout for all paths while at the same time being able to add your<Navbar />
toapp/(group1)/layout.tsx
(name group as you see fit) which will only apply to all paths within the(group1)
route group including the/account
path.I haven’t tested it, but if your
(group1)
would only contain the/account
route I think you could even simplify it as follows:i did this in my nextjs app to and it works