Handling two layouts in single dynamic route

Viewed 528

I’ve got about 8 categories of detail pages, half of which are detail pages, the other half are editorial pages. The data for these 2 page types is entirely different, and nesting one route in a subfolder is not an option.

pages/[detailPageCategory]/[slug].js
pages/[editorialPageCategory]/[slug].js

Ideally I’d create separate page components for both to separate concerns but Nextjs cannot handle two dynamic routes one the same level.

pages/[pageType]/[slug].js

Would the best idea be to handle both routes in a single dynamic route? This feels unclean, since both pages are bundled together, and I'll need to pass a prop to the page pageType={layout1|layout2} and handle both cases within the page component, not separating concerns.

const DynamicRoutePage = ({ pageType, data }) => {
  if (pageType === "detail") {
    return (
      <DetailPage {...data} />
    )
  }
  if (pageType === "editorial") {
    return (
      <EditorialPage {...data} />
    )
  }
  return null
}

Are there best practices of how to approach this? Perhaps Next’s ‘getLayout’ function?

1 Answers

You can create containers Folder, and in that you can have template for each categories pages, in this way you can separate out different pages UI's.


In the actual pages, you can [dynamic import][1] that based on the pageType.


So that the pages Template will be spitted into different chunks, and it will not be loaded all at once.

const DetailPage = dynamic(() => import('../containers/DetailPage'))
const EditorialPage = dynamic(() => import('../containers/EditorialPage'))

const DynamicRoutePage = ({ pageType, data }) => {
  if (pageType === "detail") {
    return (
      <DetailPage {...data} />
    )
  }
  if (pageType === "editorial") {
    return (
      <EditorialPage {...data} />
    )
  }
  return null
}
Related