Xaarth
Xaarth

Reputation: 1151

How to pass a component to all pages except one next js

I have a layout component which I want to pass to all the pages except the authenticate page.

I have tried using Component.name which works for dev but not for production version.

How can I do this?

  if (Component.name === 'Authenticate') {
    return (
      <Provider store={store}>
        <Component {...pageProps} />
      </Provider>
    );
  }

  return (
    <Provider store={store}>
      <Authenticate>
        <Layout>
          <Component {...pageProps} />
        </Layout>
      </Authenticate>
    </Provider>
  );

Upvotes: 2

Views: 1393

Answers (1)

Nico
Nico

Reputation: 7266

You can accomplish this using useRouter inside _app.js (recommended)

import {useRouter} from 'next/router';
function MyApp({ Component, pageProps }) {
  const router = useRouter();
  const {asPath,route,pathname } = router // pick the one that you need
  
  if(asPath === "Authenticate"){
     return (
        <Provider store={store}>
          <Component {...pageProps} />
        </Provider>
     )
  }else{
     return(
       <Provider store={store}>
          <Authenticate>
            <Layout>
               <Component {...pageProps} />
            </Layout>
        </Authenticate>
      </Provider>
     )
  }
}
 

Otherwise you can apply the same logic directly inside <Authenticate> component, and if the current route is "Authenticate" just return the childrens.

Another solution could be to use getInitialProps, but in this way CSR will be disabled and you will rely on the request instead of next.js router:

function MyApp({ Component, pageProps }) {
   const {path } = pageProps 
  
   if(path === "Authenticate"){
      return (
         <Provider store={store}>
           <Component {...pageProps} />
         </Provider>
      )
   }else{
      return(
        <Provider store={store}>
           <Authenticate>
             <Layout>
                <Component {...pageProps} />
             </Layout>
         </Authenticate>
       </Provider>
      )
   }
}
MyApp.getInitialProps = async (appContext) => { 
  return {pageProps : {
    path : appContext.ctx.pathname
  }}
}

Upvotes: 4

Related Questions