4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Next.js(React)でページ毎にレイアウトを切り替える方法

Posted at

本記事では、Next.js(React)でページ毎にレイアウトを切り替える方法を解説しています。(※TypeScriptで解説しています)

  • 特定のページにはフッター無し
  • LPページだけ違ったレイアウトにする

上記のようなページ毎にレイアウトを変えたい場合に有効です。

_app.tsxで設定する

まずは_app.tsxで設定していきます。

_app.tsx
import type { AppProps } from 'next/app'
import { NextPage } from 'next'
import { ReactElement, ReactNode } from 'react'

export type NextPageWithLayout<P = {}, IP = P> = NextPage<P, IP> & {
  getLayout?: (page: ReactElement) => ReactNode
}

type AppPropsWithLayout = AppProps & {
  Component: NextPageWithLayout
}

export default function App({ Component, pageProps }: AppPropsWithLayout) {
   const getLayout = Component.getLayout ?? ((page) => page)
   return getLayout(<Component {...pageProps} />)
}

レイアウト用のコンポーネントを作成する

続いてレイアウト用のコンポーネントを作成していきます。

Layout.tsx
import { ReactNode } from 'react'
import Header from './Header'
import Footer from './Footer'

type Props = {
  children: ReactNode
}

const Layout = ({ children }: Props) => {
  return (
    <>
      <Header />
      <main>{children}</main>
      <Footer />
    </>
  )
}

export default Layout

ページ毎に使用したいレイアウトを設定する

index.tsx
import { ReactElement } from 'react'
import Layout from '../components/layout/Layout'

const Home = () => {
  return (
    <>
      <div>ページの内容</div>
    </>
  )
}

Home.getLayout = function getLayout(page: ReactElement) {
  return <Layout>{page}</Layout>
}

export default Home

ページのgetLayoutに使用したいレイアウトを返すことで設定できます。
ページ毎に使用したいレイアウトを切り替えたい場合には、下記のように使用するレイアウト用のコンポーネントを変更します。

import TopLayout from '../components/layout/TopLayout'

Home.getLayout = function getLayout(page: ReactElement) {
  return <TopLayout>{page}</TopLayout>
}

最後に

今回はNext.jsでページごとにレイアウトを切り替える方法についてまとめました。
LPページだけ違ったレイアウトにすることも可能になるので、使い道はあるかなと思います。

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?