0

I am working with Reactjs(Nextjs) and i have different "Header" for home page and different header for rest of pages,So i want to know that how can i use different headers in nextjs,I created "Layout.js" and put "Header" and "footer" inside this and use/import this file in "_app.js", but how can we do this for different headers ? Here is my _app.js file

import React from 'react';
import App from 'next/app';
import Layout from '../components/layout'
import type { AppProps } from 'next/app'
function MyApp({ Component, pageProps }: AppProps) {
  return (
    <>
     <Layout>
     <Component {...pageProps} />
     </Layout>
    </>
   );
}
export default MyApp
1

1 Answer 1

1
  1. Create a new layout for your homepage, say HomeLayout.
  2. Attach this HomeLayout as a property getLayout on your homepage component.
// src/pages/index.js
import HomeLayout from 'layout/HomeLayout';

const Home = () => {
    return (
        <h1>Home page </h1>
    );
};

Home.getLayout = HomeLayout;

export default Home;
  1. Use this newly attached property on _app.js to conditionally determine which layout to render. If there exists getLayout on a component, we use that layout else we will fallback to our default Layout.
// _app.js
import Layout from '../components/layout'

const App = ({ Component, pageProps }) => {
    const AppLayout = Component.getLayout || Layout;
    return (
      <AppLayout>
        <Component {...pageProps} />
      </AppLayout>
    );
};

export default App;

Reference:

  1. https://nextjs.org/docs/basic-features/layouts
Sign up to request clarification or add additional context in comments.

2 Comments

i am getting following error "Property 'getLayout' does not exist on type 'FunctionComponent<{}> & { getInitialProps?(context: NextPageContext): {} | Promise<{}>; }"
@Rick did you solve that? Seems like a type error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.