Introduction
Steps up to Installation
To enable use within your project, please refer to the following guide for installation steps:
https://it.hasethblog.com/en/archive/70
Error When Writing Directly in a Dynamic Page
TypeError: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it.
Since App Router renders everything as a server component by default, you must explicitly add "use client"
to treat a file as a client component.
Typically, placing "use client"
at the top of the file will resolve this error.
However, when rendering with SSG, that approach does not work.
When creating dynamic pages with SSG in App Router, you use generateStaticParams
, which is a server component. Therefore, you cannot use "use client"
in that context.
You can display MDX on a dynamic page by following the method below.
Steps
Create src/md/md.mdx
Write the following:
# Welcome to my MDX page!
Create src/component/mdRelay.tsx
The import identifier can be anything; I used Mdx
.
This file acts as a relay for the MDX file.
Since this component must use a client component, add "use client"
:
"use client"
import Mdx from '@/md/md.mdx'
const MdRelay = () => {
return (
<>
<Mdx />
</>
);
}
export default MdRelay;
Create src/app/[page]/page.tsx
Import the relay file created earlier and render it inside the component:
import { NextPage } from 'next';
import MdRelay from '@/component/mdRelay';
type Props = { // omitted }
const Page: NextPage<Props> = (props) => {
// omitted
return (
<>
<MdRelay />
</>
);
};
export default Page;
export const generateStaticParams = async () => {
// omitted (assuming pages 1 and 2 exist)
return [{ page: '1' }, { page: '2' }]
}
With this setup, you can use MDX on dynamic pages without issue.
References
nextjs.org GenerateStaticParams
[NEXT-1049] use client with generateStaticParams will opt out of static generation #46735
Conclusion
It's not straightforward, is it?
Since I'm only generating static sites, to be honest, there's not much need for me to use the App Router.
Perhaps App Router is recommended because it's optimized for SSR?