emAyush56
emAyush56

Reputation: 161

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

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

Upvotes: 11

Views: 8348

Answers (1)

Ahmed Abdelbaset
Ahmed Abdelbaset

Reputation: 4728

  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

Upvotes: 12

Related Questions