일부 페이지에만 요소를 추가하는
export default function SearchableLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div>
<div>임시 서치바</div>
{children}
</div>
);
}
import SearchableLayout from "@/components/searchable-layout";
import { useRouter } from "next/router";
export default function Page() {
const router = useRouter();
console.log("router", router);
const { q } = router.query;
return <h1>Search {q}</h1>;
}
💛// 객체여서 메서드를 추가할 수 있음
Page.getLayout = (page: React.ReactNode) => {
return <SearchableLayout>{page}</SearchableLayout>;
};
그러고 app컴포넌트에 설정
export default function App({ Component, pageProps }: AppProps) {
const getLayout = Component.getLayout;
return <GlobalLayout>
{getLayout(<Component {...pageProps} />)}
</GlobalLayout>;
}
근데 getLayout가 없으면 어떡해?
예외처리하기
const getLayout = Component.getLayout ?? ((page) => page);
import GlobalLayout from "@/components/global-layout";
import SearchableLayout from "@/components/searchable-layout";
import "@/styles/globals.css";
import { NextPage } from "next";
import type { AppProps } from "next/app";
import { ReactNode } from "react";
//타입추가
// NextPage: 기존 제공하는 페이지
type NextPageWithLayout = NextPage & {
getLayout?: (page: ReactNode) => ReactNode;
};
export default function App({
Component,
pageProps,
}: AppProps & { Component: NextPageWithLayout }) {
const getLayout = Component.getLayout ?? ((page: ReactNode) => page);
return <GlobalLayout>{getLayout(<Component {...pageProps} />)}</GlobalLayout>;
}