Reputation: 21
I am using nextjs and next-mdx-remote for blogging static websites.
/src/app/blog/post/post1
import dynamic from 'next/dynamic';
import { getPostBySlug } from '@/lib/mdx';
import MDXComponents from '@/components/mdx-components';
const MDXRemote = dynamic(() => import('next-mdx-remote').then(mod => mod.MDXRemote), {
ssr: false,
});
export default async function BlogPost() {
const slug = 'post1';
const { mdxSource, frontMatter } = await getPost(slug);
if (!mdxSource) {
return <div>404 - maaz here</div>;
}
return (
<div>
<h1>{frontMatter.title}</h1>
<MDXRemote {...mdxSource} components={MDXComponents} />
</div>
);
}
Due to this MDXRemote { Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
while in above code I use getPost
this is place at /src/lib/mdx.tsx
and this function is below
export const getPost = async (slug: string) => {
const filePath = path.join(contentDir, `${slug}.mdx`);
try {
const source = fs.readFileSync(filePath, 'utf8');
const { content, data } = matter(source);
const mdxSource = await serialize(content);
return { mdxSource, frontMatter: data };
} catch (error) {
console.error('Error reading file:', error);
return { mdxSource: null, frontMatter: null };
}
};
So, kindly tell me what is the main reason for above error. I tried to solve this using many methods using getStaticProps()
but nextjs 13 version is not applicable in /app dir so this also gives error
I am trying to convert mdx file into react component and use it in my site using serialize and MDXRemote but this error occur Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
Upvotes: 2
Views: 171
Reputation: 567
You are using the app directory which does not need serialize
and should be imported from next-mdx-remote/rsc
take a look at the section titled "React Server Components (RSC) & Next.js app Directory Support" in their documentation
Upvotes: 1