Gurveer
Gurveer

Reputation: 127

Next.js conditional layout

I have changed _app.js to load layout depending upon which page is loaded. All work fine in development mode but once I create build it fails to get "Component.name" and returns empty value. Any suggestions please?

my _app.js

import "../styles/globals.css";
import Layout from "../components/Layout";

function MyApp({ Component, pageProps }) {
  switch (Component.name) {
    case "Home":
      return <Component {...pageProps} />;
    default:
      return (
        <Layout>
          <Component {...pageProps} />{" "}
        </Layout>
      );
  }
}

export default MyApp;

Upvotes: 3

Views: 6750

Answers (2)

sanket benade
sanket benade

Reputation: 11

We can use useRouter for this case. As if when we create 404 page, nextJs navigates unknown paths to 404.js we can take advantage of this feature.

//Layout.js

import Header from "./header.js"
import Footer from "./footer.js"
import Sidebar from "./Sidebar.js"
import { useRouter } from "next/router"

export default function Layout({ children }) {
  const router = useRouter()
  console.log("router", router)

  if (router.route === "/404") {
    return (
      <>
        <main>{children}</main>
      </>
    )
  }

 if(router.router === "/dashboard") {
 return (
 <Sidebar>{children}</Sidebar>
 )
 }
  return (
    <>
      <Header />
      <main>{children}</main>
      <Footer />
    </>
  )
}

//_app.js

  <Component {...pageProps} />

Upvotes: 0

Danila
Danila

Reputation: 18476

name is empty because code minification removes this values or obfuscates them, so you should not depend on the names of classes or functions.

For per page layout please follow this official guide

Basically you create getLayout function for each page, and this function should return the layout:

import Layout from '../components/layout'
import NestedLayout from '../components/nested-layout'

export default function Page() {
  return {
    /** Your content */
  }
}

Page.getLayout = function getLayout(page) {
  return (
    <Layout>
      <NestedLayout>{page}</NestedLayout>
    </Layout>
  )
}

in _app use it like that:

export default function MyApp({ Component, pageProps }) {
  // Use the layout defined at the page level, if available
  const getLayout = Component.getLayout || ((page) => page)

  return getLayout(<Component {...pageProps} />)
}

Upvotes: 5

Related Questions