ReasonJun

Next.js : Apply common layout 본문

Frontend/Next.js

Next.js : Apply common layout

ReasonJun 2023. 6. 18. 12:51
728x90

components/Layout.js

Create a common component separately as a layout.js file in the component folder and apply it to pages/_app.js.

 

pages/_app.js => Setting overall position in Component.

import '@/styles/globals.css';
import Layout from '@/components/Layout';

export default function App({ Component, pageProps }) {

  const getLayout = Component.getLayout || ((page) => <Layout>{page}</Layout>);

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

components/Layout.js => Setting common layout

import Head from 'next/head';

import { Inter } from 'next/font/google';

// Because it is a component, not a page, serverside rendering cannot be performed.

const inter = Inter({ subsets: ['latin'] });

export default function Layout({ children }) {
  return (
    <>
      <Head>
        <title>Create Next App</title>
        <meta name='description' content='Generated by create next app' />
        <meta name='viewport' content='width=device-width, initial-scale=1' />
        <link rel='icon' href='/favicon.ico' />
      </Head>
      <main>{children}</main>
    </>
  );
}

Nexted component / Apply multiple Layout

component/SubLayout.js => Setting common Layout of children

import Link from 'next/link';

// Because it is a component, not a page, serverside rendering cannot be performed.

export default function SubLayout({ children }) {
  return (
    <div>
      <h1>
        <Link href='/'>
          <div>HOME로</div>
        </Link>
      </h1>
      {children}
    </div>
  );
}

pages/ssg.js => Setting subLayout in children pages

import Layout from '@/components/Layout';
import SubLayout from '@/components/SubLayout';

export async function getStaticProps() {
  console.log('server');
  return {
    props: { time: new Date().toISOString() },
    revalidate: 1,
  };
}

export default function SSG({ time }) {
  return (
    <>
      <main>
        <h1>{time}</h1>
      </main>
    </>
  );
}

SSG.getLayout = function getLayout(page) {
  return (
    <Layout>
      <SubLayout>{page}</SubLayout>
    </Layout>
  );
};

pages/csr.js => Setting subLayout in children pages

import Layout from '@/components/Layout';
import SubLayout from '@/components/SubLayout';
import { useEffect, useState } from 'react';

export async function getServerSideProps() {
  return {
    props: { time: new Date().toISOString() },
  };
}

export default function CSR() {
  const [time, setTime] = useState();

  useEffect(() => {
    console.log('client');
    setTime(new Date().toISOString());
  }, []);

  return (
    <>
      <h1>{time}</h1>
    </>
  );
}

CSR.getLayout = function getLayout(page) {
  return(
    <Layout>
      <SubLayout>{page}</SubLayout>
    </Layout>
  )
}
728x90
Comments