DocsBlogChangelog

Rendering Examples

Examples can be rendered using the router of your preferred Server Component framework. This guide will show you how to render examples using Next.js, but the same principles can be applied to other frameworks.

Templating

Each framework should have a concept of templating and routing. To render examples, query the metadata collected from createSource. Using Next.js as an example framework, we can create a custom page that will render the example based on the name of the example file:

components/[component]/examples/[example]/page.tsx
import { notFound } from 'next/navigation'
import { createSource } from 'mdxts'

const allComponents = createSource('components/**/*.tsx')

export const dynamic = 'force-static'

export async function generateStaticParams() {
  return (await allComponents.examplePaths()).map((pathname) => ({
    example: pathname,
  }))
}

export default async function Page({
  params,
}: {
  params: { example: string[] }
}) {
  const singlePackage = await allComponents.get(params.example.slice(0, -1))
  const example = await allComponents.getExample(params.example)

  if (!singlePackage || !example) {
    return notFound()
  }

  return <example.moduleExport />
}
Last updated