Next.js Opt out of Layout Component for specific pages from _app.js

by checking the appProps.router.pathname property passed to it.

way 1

function MyApp({ Component, pageProps, ...appProps }: AppProps) {

  // make function that will return the children based on router.pathname

  const getContent = () => {
    // array of all the paths that doesn't need layout
    if ([`/dashboard`].includes(appProps.router.pathname))
      return <Component {...pageProps} />;

    return (
      <Layout>
        <Component {...pageProps} />{" "}
      </Layout>
    );
  };
   

  return <ApplicationWrapper>{getContent()}</ApplicationWrapper>;
}

way 2

function MyApp({ Component, pageProps, ...appProps }: AppProps) {
  
  // use a LayoutComponent variable 
  // that switches to actual Layout or React.Fragment (no layout) 
  // accordingly to pathname

  const isLayoutNeeded = [`/dashboard`].includes(appProps.router.pathname);
  const LayoutComponent = isLayoutNeeded ? Layout : React.Fragment;

  return (
    <ApplicationWrapper> 
      <LayoutComponent>
        <Component />
      </LayoutCompnent>
    </ApplicationWrapper>
  );
}

TIP:

you can use path.startsWith to check all the paths,
example

if(router.pathname.startsWith(`/dashboard`))

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)