Dynamic data-driven pages with code components

Let’s say that you already have data-fetching code components, either created by yourself, or from the Plasmic component store (such as components that show CMS or commerce data).

You know that you can create (static) pages that include this data. But you can also create dynamic pages/routes.

Examples include:

  • A blog with one page per post.
  • A storefront with one page per product.

(If you are looking to pass dynamic data into simple static Plasmic designs that don’t use code components, see how to pass overrides to the component API.)

The approach is to take a single page designed in Plasmic, and communicate to it to render alternate data. This essentially uses that page as a template.

The way to communicate to the component depends on how the component works, but most typically, the component takes a prop telling it what data to fetch/render, so you pass in the prop you want via the component overrides API.

Example: statically generated /products/[slug] pages in Next.js

Here’s an example showing how to display a product at /products/[slug], using Next.js dynamic routes.

You can see a complete working example of this approach.

We’ll assume we’re fetching data using the data-fetching components in the Plasmic CMS.

Let’s say our page includes fetcher as a named element that is an instance of the Plasmic CMS data-fetching component. These components take a where prop that accepts a query object indicating what specific CMS data to fetch. This is specific to the Plasmic CMS data-fetching component—other data-fetching components will have different props.

In getStaticProps we know the slug of the currently requested page, so we forward that to the fetcher.

pages/products/[slug].tsx
Copy
export const getStaticProps: GetStaticProps<ProductPageProps, ProductParams> = async (context) => {
const slug = context.params?.slug;
if (!slug) {
throw new Error('Missing slug');
}
const plasmicData = await PLASMIC.fetchComponentData(pagePath);
const queryCache = await extractPlasmicQueryData(
<PlasmicRootProvider loader={PLASMIC} prefetchedData={plasmicData}>
<PlasmicComponent
component={pagePath}
componentProps={{
fetcher: { where: { slug } }
}}
/>
</PlasmicRootProvider>
);
return { props: { plasmicData, queryCache, slug } };
};

Ultimately we render that same data in the final page:

Copy
const ProductPage: NextPage<ProductPageProps> = ({ plasmicData, queryCache, slug }) => {
return (
<PlasmicRootProvider loader={PLASMIC} prefetchedData={plasmicData} prefetchedQueryData={queryCache}>
<PlasmicComponent
component={pagePath}
componentProps={{
fetcher: { where: { slug } }
}}
/>
</PlasmicRootProvider>
);
};

The above could have been used with SSR or SSG, but let’s say we want to statically generate all the paths. See the linked complete example for the associated getStaticPaths() function.

Give feedback on this page