-
SummaryI followed the docs for importing MDX files dynamically, and I'm getting this createContext error in a server component where I'm not using createContext. in I'm not using If I add This entire app is built following the guides. So I haven't really done much customizations yet that I would expect to get me in trouble. thank you Additional information
ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
|
Hi Khayden73, thats why importing it in a server throws error, adding use client does fix it but it breaks async/await... Keep the page as a server component, move the mdx render into a separate client component then dynamically import that client and then pass the MDX to it. |
Beta Was this translation helpful? Give feedback.
-
|
thanks for the explanation. It's strange that would be the exact example from the docs and it doesn't work as shown. So I added this inside my server component const DynamicClientPost = dynamic(() => import('./ClientPost'), {
loading: () => <p>loading...</p>
})
export default async function Page({params}: { params: Promise<{ slug: string }> }) {
const {slug} = await params;
return (
<div>
<h2>blog post page</h2>
<h3>slug: {slug}</h3>
<DynamicClientPost slug={slug}/>
</div>
)
}But then in ClientPost.tsx I still can't seem to dynamically grab the mdx file and render it without running into an error. And this is what I have inside ClientPost.tsx 'use client'
import {ReactNode, useEffect, useState} from "react";
interface ClientPostProps {
slug: string
}
export default function ClientPost({slug}: ClientPostProps) {
const [Post, setPost] = useState<ReactNode | null>(null);
useEffect(() => {
if (Post === null) {
import(`@/content/${slug}.mdx`)
.then((module) => {
const {default: MDXContent} = module;
setPost(MDXContent)
});
}
});
return (
<div>
{Post}
</div>
);
} |
Beta Was this translation helpful? Give feedback.
-
|
Hi @khayden73 ClientPost.tsx 'use client'
import { useEffect, useState } from 'react'
type Props = { slug: string }
export default function ClientPost({ slug }: Props) {
const [MDX, setMDX] = useState<React.ComponentType | null>(null)
useEffect(() => {
let cancelled = false
;(async () => {
const mod = await import(`@/content/${slug}.mdx`)
if (!cancelled) setMDX(() => mod.default) // : function wrapper
})()
return () => {
cancelled = true
}
}, [slug])
if (!MDX) return <p>loading...</p>
return <MDX />
}app/blog/[slug]/page.tsx import ClientPost from './ClientPost'
export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
return (
<div>
<h2>blog post page</h2>
<ClientPost slug={slug} />
</div>
)
}if you want use of lazy-load : import dynamic from 'next/dynamic'
const ClientPost = dynamic(() => import('./ClientPost'), {
ssr: false,
loading: () => <p>loading...</p>,
}) |
Beta Was this translation helpful? Give feedback.
Hi @khayden73
ClientPost.tsx
app/blog/[slug]/page.tsx