Tạo layout trong NextJS

Tạo layout trong NextJS

Tags
Published

Layout trong NextJS

  • Layout là một cái khung để chứa các component trong app
notion image
Bắt đầu nào
_app.js
function MyApp({ Component, pageProps }) { const Layout = Component.Layout || (({ children }) => <>{children}</>); return ( <Layout> <Component {...pageProps} />; </Layout> ); } export default MyApp;
components/[layoutxxx].js
export default function Te({ children }) { return ( <div className="bg-blue-700"> <h1 className="text-3xl text-gray-600">Layout</h1> <div>{children}</div> </div>); }
page/[pagexxxx].js
import Te from "components/layouts/Te.js"; function Test() { return ( <> <h1 className="text-6xl ml-40 relative ">Hello</h1> </>); } Test.Layout = Te; export default Test; // layout for page

Chú ý

thư mục layout phải ở trong folder component. Nếu đang sử dụng Tailwind CSS (Vẫn có thể để chỗ khác những phải tuỳ chỉnh lại config)
Restart lại server nếu Layout không hiện

Tham khảo