리액트/NextJS
[NextJs] layout
another problem
2023. 6. 20. 22:21
https://dev.to/jaredm/guide-to-layouts-and-page-specific-layouts-in-nextjs-k2m
Guide to Layouts and Page Specific Layouts in NextJS
Layouts are a powerful abstract concept in NextJS. It is a declarative way of telling Next the...
dev.to
https://www.codeconcisely.com/posts/nextjs-multiple-layouts/
How to Use Multiple Layouts in Next.js - Code Concisely
Learn how to use more than one layout in Next.js. Create a default layout that is used in every page. Override the default layout in a page with another layout.
www.codeconcisely.com
index.tsx(조건부로 layout 설정하기)
import LayoutHome from "@/components/LayoutHome";
//1. 렌터링할 AlternativeLayoutPage
export default function AlternativeLayoutPage() {
return <>AlternativeLayoutPage</>;
}
AlternativeLayoutPage.getLayout = function (page: any) {
//2. LayoutHome에 prop.children 형식으로 AlternativeLayoutPage을 보내기 세팅
return <LayoutHome>{page}</LayoutHome>;
};
layoutHome.tsx
type Props = {
children: React.ReactNode;
};
export default function LayoutHome(props: Props) {
return (
<div>
//3-1.아래 AlternativeLayoutPage가 있을 때 랜더링 코드
<header>hi</header>
//3. index.tsx에서 받아온 AlternativeLayoutPage 랜더링하기
<slot>{props.children}</slot>
</div>
);
}
app.tsx
import SideNavbar from "@/components/SideNavbar";
import "@/styles/globals.css";
import type { AppProps } from "next/app";
export default function App({ Component, pageProps }: AppProps) {
const renderWithLayout =
//4. AlternativeLayoutPage 적용 설정 코드
// 4-1. Component.getLayout : AlternativeLayoutPage.getLayout이 설정되어 있는 페이지는 그 레이아웃을 보여주고
Component.getLayout ||
// 4-2. 그렇지 않다면 SideNavbar을 전페이지에 적용해
function (page: any) {
return <SideNavbar>{page}</SideNavbar>;
};
//AlternativeLayoutPage 적용 전 코드
// return (
// <SideNavbar>
// <Component {...pageProps} />
// </SideNavbar>
// )
return renderWithLayout(<Component {...pageProps} />);
}