Is there a way to remove the base layout for a specific page in NextJS 13 ? I have a general layout for mosts of my views, but some of them require a separated layout, I don't find any solution now.
I've tried to make "groups" of folders with the same layout at the app/ root, but this way is really annoying and kills the project files arborescence.
SOLUTION :
The answer solution is great, but I advise you doing so for general purpose :
https://stackoverflow.com/a/76251557/21820614
Personally, for my project structure, I needed a route which contains a layout, with a header etc, and another route which has no layout at all. I used the link provided above and I made ghost groups for my "root" routes.
BUT, I also needed differents contents in the header (contained in the layout), depending on the route I was in. For doing so, I used the LayoutProvider, with the answer below, and it works great !
NextJS 13
way to achieve this is by using Routing Groups
in short, ONLY include layout elements that all children need, and use grouping
to share layout in common sections
example of the app
directory file structure:
-- (auth)/ # only for grouping, does not add to url
/signin/page.tsx
/singout/page.tsx
/singup/page.tsx
/layout.tsx # shared between auth group only
-- (dashboard)/
/page.tsx # home page
/layout.tsx
-- layout.tsx # main layout, used in ALL pages
for more info, take a look at these two example projects:
With Next.js <13, the Root Layout can not be set to a Client Component. This means that a shared layout is not re-rendered during navigation. Therefore, you need to create a layout page, similar to a provider, that can wrap the Root Layout. The layout page has to be client component.
/app
): // Use the client directive for using usePathname hook.
'use client'
// Use usePathname for catching route name.
import { usePathname } from 'next/navigation';
export const LayoutProvider = ({ children }) => {
const pathname = usePathname();
return (
<>
{pathname === "/posts" && <h1>Welcome to Posts page!</h1>}
{children}
</>
)
};
/app/layout.js
):// Import your layout page
import { LayoutProvider } from './LayoutProvider'
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<LayoutProvider>
{children}
</LayoutProvider>
</body>
</html>
)
}
Further reading:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With