👏
Next.jsにスタイルを適用させる方法 備忘録
準備
header
components/Header/Header.tsx
export const Header = () => {
return <header>header</header>
}
footer
components/Footer/Footer.tsx
export const Footer = () => <footer>footer</footer>
layout
layout/Layout.tsx
import { ReactElement } from 'react'
import { Footer, Header } from '@src/component/ui'
type LayoutProps = Required<{
readonly children: ReactElement
}>
export const Layout = ({ children }: LayoutProps) => (
<>
<Header />
{children}
<Footer />
</>
)
Nextの型拡張
types/index.d.ts
import type { NextPage, NextPageWithLayout } from 'next'
import type { AppProps } from 'next/app'
import type { ReactElement } from 'react'
declare module 'next' {
type NextPageWithLayout<P = {}, IP = P> = NextPage<P, IP> & {
getLayout?: (page: ReactElement) => ReactElement
}
}
declare module 'next/app' {
type AppPropsWithLayout<P = {}> = AppProps<P> & {
Component: NextPageWithLayout<P>
}
}
_app.tsx
_app.tsx
import type { AppPropsWithLayout } from 'next/app'
function MyApp({ Component, pageProps }: AppPropsWithLayout) {
const getLayout = Component.getLayout ?? ((page) => page)
return getLayout(<Component {...pageProps} />)
}
export default MyApp
pages/index.tsx
pages/index.tsx
import type { NextPageWithLayout } from 'next'
import { AboutPage } from '@src/component/pages/About'
import { Layout } from '@src/layouts'
const About: NextPageWithLayout = () => <AboutPage />
About.getLayout = (page) => <Layout>{page}</Layout>
export default About
参考
Discussion