I tried to create a custom component with contentlayer, but it was not working as expected. At first, I thought that I have to import the custom component inside the .mdx file. But, every time I do so, contentlayer will throw errors and not transform my .mdx file to json format. As I was digging through the problem, I found a solution which I shared below.
// page.tsx
import { useMDXComponent } from "next-contentlayer/hooks";
const Button = () => {
return <button>Click me</button>;
};
const customComponents = {
Button
};
const SinglePost = ({ article }) => {
const MDXContent = useMDXComponent(article.body.code);
return (
<>
<MDXContent components={customComponents} />
</>
);
};
// file.mdx
### Call Button directly in your mdx file. No need to import it, it works automatically.
<Button />