How to use a completely different layout in a nested component in NextJS App Router?
Asked Answered
J

1

7

enter image description here

Above is the structure of my app router.

It has a root layout that has to be shared with every one. Now inside the login component there is another layout.jsx that should NOT share the root layout. Instead it should override the root layout and use the local layout inside login's page.

How to achieve that?

I tried to write the layout of login like the following:

enter image description here

It partially works, but has the following issues:

  1. For a fraction of second the rootlayout is shown, there is a flicker. And then the login's layout is shown.
  2. I get the following errors

2.1 unhandled error 1

Unhandled Runtime Error Error: Text content does not match server-rendered HTML. Warning: Text content did not match. Server: "Root layout" Client: "Login page" See more info here: https://nextjs.org/docs/messages/react-hydration-error

2.2 unhandled error 2

Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.

Following is the root layout file, adding for reference:

enter image description here

I am using next js 14

Jessi answered 12/1 at 12:39 Comment(0)
S
8
  1. Make your root app/layout.tsx as basic as:
export default function RootLayout({children}) {
  return (
     <html>
        <body>{children}</body>
     </html>
   )
}
  1. In your app/login/layout.tsx: make the layout for the login page without <html> and <body> tags.

  2. Wrap your rest app in a route group:

app/
- layout.tsx        <-- root layout 
- login/
  - layout.tsx      <-- login layout 
  - page.tsx
  - ...
- (any-name-for-the-group)
  - layout.tsx      <-- app layout
  - page.tsx
  - about/
    - page.tsx
  - ...

Learn more about route group: https://nextjs.org/docs/app/building-your-application/routing/route-groups

Sourdough answered 12/1 at 14:9 Comment(2)
Though your code is not the exact solution that I needed. But the route groups was the solution I needed. Thank you.Jessi
@Jessi Consider adding an answer you are allowed to answer your own question.Auditor

© 2022 - 2024 — McMap. All rights reserved.