I am working on a Next.js 13 project where I have a route named problems/[slug]. On the first level of this route (e.g., problems/react), I have a sidebar and a content section, which I am displaying using a layout.tsx.
However, on the next nested level of the route (e.g., /problems/react/test-problem), I want to use a different layout instead of the original one. Is there a way to achieve this?
Note: I am looking for an app directory-based approach
In Next.js 13, you can use the usePathname hook to determine which page you are on and then logically show or hide it:
const pathname = usePathname(); const show_Navbar_Sidebar = pathname === '/about' || pathname === '/signup' ? false : true;
You can keep the structure of the pages folder as shown below
pages/
problems/
[slug]/
- index.js // will match for /problems/[:slug]
- [problem].js // will match for /problems/[:slug]/[:problem]
If you need multiple layouts, you can add a property getLayout to your page, allowing you to return a React component for the layout. This allows you to define the layout on a per-page basis. Since we're returning a function, we can have complex nested layouts if desired.
// pages/problems/[slug]/index.js
import StandardLayout from '../components/StandardLayout'
export default function ProblemMainPage() {
return (
/** Your content */
)
}
ProblemMainPage.getLayout = function getLayout(page) {
return (
<StandardLayout>
{page}
</StandardLayout>
)
}
// pages/problems/[slug]/[problem].js
import AnotherLayout from '../components/AnotherLayout'
export default function ProblemDetail() {
return (
/** Your content */
)
}
ProblemDetail.getLayout = function getLayout(page) {
return (
<AnotherLayout>
{page}
</AnotherLayout>
)
}
Update your pages/_app.js file
// pages/_app.js
export default function MyApp({ Component, pageProps }) {
// Use the layout defined at the page level, if available
const getLayout = Component.getLayout || ((page) => page)
return getLayout(<Component {...pageProps} />)
}
Learn more about it on Next.js documentation here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With