vercel / next.js

The React Framework
https://nextjs.org
MIT License
127.1k stars 27.01k forks source link

Nested layout inheriting classes from outer layout on page load #69666

Open Zain-ul-din opened 2 months ago

Zain-ul-din commented 2 months ago

Link to the code that reproduces this issue

https://github.com/Zain-ul-din/mdx-templates

To Reproduce

I have no idea this is a feature or bug but it's not working as I want it to work. I'm using next js app router and my directory structure is following

- app
  - docs
    page.tsx
    layout.tsx
 layout.tsx
 page.tsx

I'm trying to add classes inside docs/layout.tsx body it's working on runtime but as I refresh the page it's being replaced by root layout app/layout.tsx body classes.

// app/layout.tsx
export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body className={`${inter.className} root`}>{children}</body>
    </html>
  );
}
// app/docs/layout.tsx
export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body className={`${inter.className} prose`}>
        <h1 className="text-2xl my-4">
          👑 This is root {`'/(docs)/docs/layout.tsx'`}
        </h1>
        {children}
      </body>
    </html>
  );
}

https://github.com/user-attachments/assets/42ac0b7d-1327-4d05-9452-8258b039265c

Current vs. Expected behavior

Nested layout classes should not be overridden by root layout.

Provide environment information

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 10 Pro
  Available memory (MB): 15742
  Available CPU cores: 16
Binaries:
  Node: 20.10.0
  npm: N/A
  Yarn: N/A
  pnpm: N/A
Relevant Packages:
  next: 14.2.7 // Latest available version is detected (14.2.7).
  eslint-config-next: 14.2.7
  react: 18.3.1
  react-dom: 18.3.1
  typescript: 5.5.4
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Navigation

Which stage(s) are affected? (Select all that apply)

next dev (local)

Additional context

Repo Link: https://github.com/Zain-ul-din/mdx-templates

Thank you in advance

r-sp commented 5 days ago

quick review from your video, i saw duplicated export default function RootLayout(){} from app/layout.tsx and app/docs/layout.tsx might be the problem.

you should wrap any mdx content with shared layout.

layout: app/docs/layout.tsx

export default function MdxLayout({ children }: { children: React.ReactNode }) {
  // Create any shared layout or styles here
  return <div style={{ color: 'blue' }}>{children}</div>
}

page: app/docs/page.mdx

# Welcome to my MDX page!

[!NOTE] i know that you're trying to add some classes inside docs/layout.tsx, but you can't import another root-layout inside root-layout.