简体   繁体   中英

NextJS dynamic routes with dynamic component

I want to create 3 dynamic pages with different render component for each.

// components/AboutPage.js
export default function AboutPage({ template }){
  return <h1>{template}</h1>
}
// components/ContactPage.js
export default function ContactPage({ template }){
  return <h1>{template}</h1>
}
// components/BlogPage.js
export default function BlogPage({ template }){
  return <h1>{template}</h1>
}

And the route file.

// pages/[slug].js
import AboutPage from '../components/AboutPage'
import BlogPage from '../components/BlogPage'
import ContactPage from '../components/ContactPage'

export default function DynamicPage({ page }) {
  switch (page?.template) {
    case 'aboutPage':
      return <AboutPage {...page} />
    case 'blogPage':
      return <BlogPage {...page} />
    case 'contactPage':
      return <ContactPage {...page} />
    default:
      return null
  }
}

export const getStaticPaths = () => {
  const page = {
    template: 'aboutPage',
    slug: 'about'
  }
  return {
    props: {
      page
    }
  }
}

export const getStaticPaths = () => {
  const fetchedData = [
    {
      template: 'aboutPage',
      slug: 'about'
    },
    {
      template: 'contactPage',
      slug: 'contact'
    },
    {
      template: 'blogPage',
      slug: 'blog'
    }
  ]

  return {
    paths: fetchedData.map(({ slug }) => ({ params: {slug} })),
    fallback: 'blocking'
  }
}

My site is generated on build time, and my concern with this is the final JavaScript bundle size may include all 3 components and even when page is AboutPage for example.

I have not seen any related solution, NextJS has dynamic() but not sure if it helps my case? Or any way how can I make this work?

You can use next/dynamic .

Add:

const AboutPage = dynamic(
  () => import("../components/AboutPage"),
);

instead of

import AboutPage from '../components/AboutPage'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM