you can use the getLayout function to define a custom layout for a page, including dynamic routes. Here's an example of how you can use getLayout
to apply the DashboardLayout
to all pages under the /dashboard
route:
Define your custom DashboardLayout component:
import React from 'react';
import Navbar from '../components/Navbar';
const DashboardLayout = ({ children }) => {
return (
<>
<Navbar />
<main>{children}</main>
</>
);
};
export default DashboardLayout;
In your dynamic route file (pages/dashboard/[id].jsx)
, define the getLayout function to return the DashboardLayout
:
import DashboardLayout from '../../layouts/DashboardLayout';
const DashboardPage = ({ id }) => {
return <h1>Dashboard page with ID: {id}</h1>;
};
DashboardPage.getLayout = function getLayout(page) {
return <DashboardLayout>{page}</DashboardLayout>;
};
export default DashboardPage;
Note that the getLayout
function takes in the page as an argument, representing the page component wrapped with the layout. You can then return the DashboardLayout
component with the page as its child.
To extract the id parameter from the URL, you can use the useRouter
hook from the next/router
module:
import { useRouter } from 'next/router';
import DashboardLayout from '../../layouts/DashboardLayout';
const DashboardPage = () => {
const router = useRouter();
const { id } = router.query;
return <h1>Dashboard page with ID: {id}</h1>;
};
DashboardPage.getLayout = function getLayout(page) {
return <DashboardLayout>{page}</DashboardLayout>;
};
export default DashboardPage;
In this example, we use the useRouter
hook to access the query object containing the dynamic route parameters. We can then extract the id parameter from the query object and use it in our component.
With these changes, your dynamic route should now use the DashboardLayout
component.
app/dashboard/[id]/page.jsx
? – Captor