I want to build 2 different layouts, 1 for my admin panel which will have a sidebar and main area and 1 for my website which will have header, navbar, main area and a footer. I just want 2 layouts, don't want to define layout per page. Is there any logic to do that in Next.JS?
CodePudding user response:
In your _app.js
you can check which layout should be use by pageProps
define per page
const App = ({ Component, pageProps }) => {
const getLayout =
pageProps.typeLayout == 'admin' ? ((page) => <AdminLayout children={page} />)
: ((page) => <FrontLayout children={page} />);
return (
<>
{getLayout(<Component {...pageProps} />, pageProps)}
</>
);
};
and in per pages, you should return props in getServerSideProps
export const getServerSideProps = async (ctx) => {
return {
props: {
typeLayout : 'admin',
},
};
};
or you can define layout by router name
const App = ({ Component, pageProps, router }) => {
const getLayout =
router.pathname.includes('/admin') ? ((page) => <AdminLayout children={page} />)
: ((page) => <FrontLayout children={page} />);
return (
<>
{getLayout(<Component {...pageProps} />, pageProps)}
</>
);
};
CodePudding user response:
My main problem is that I have so many admin pages and so many front pages. So, I don't want to have per page solution for this project. So, I think if I could use pathname instead. My admin panel routes starts with '/admin-panel', So I checked for that. The following logic in _app.js
works for me
function MyApp({ Component, pageProps, router }) {
const adminPanel = router.route.startsWith('/admin-panel') ? true : false
const getLayout =
adminPanel ? ((page) => <AdminLayout children={page} />)
: ((page) => <FrontLayout children={page} />);
return (
<>
{getLayout(<Component {...pageProps} />, pageProps)}
</>
);