Next.js Discord

Discord Forum

Does next-mdx-remote support custom components

Answered
Rex posted this in #help-forum
Open in Discord
RexOP
I was working on some docs for a site and we are using md & mdx.

Looking at https://nextjs.org/docs/pages/building-your-application/configuring/mdx#custom-elements it says we can use custom elements / components but when trying to do so using [next-mdx-remote](https://nextjs.org/docs/pages/building-your-application/configuring/mdx#remote-mdx) it just does not seem to work (i.e its not using the custom components)

I'm unsure if I'm placing the mdx-components.tsx file in the wrong spot or what. I've tried a few locations i.e src/mdx-components.tsx src/pages/mdx-components.tsx and just in the main directory but still nothing.
Answered by Rex
import { readFile } from "fs/promises";
import { serialize } from "next-mdx-remote/serialize";
import { MDXRemote, MDXRemoteSerializeResult } from "next-mdx-remote";
import { useMDXComponents as useCustomMdxComponents } from "../../mdx-components.tsx";
import { useMDXComponents } from "@mdx-js/react";

interface Props {
    mdxSource: MDXRemoteSerializeResult;
}

const RemoteMdxPage = ({ mdxSource }: Props) => {
    const baseComponents = useMDXComponents();
    const components = useCustomMdxComponents(baseComponents);

    return <MDXRemote {...mdxSource} components={components}  />;
};

const getStaticProps = async () => {
    const mdxText = await readFile("public/docs/docs/Intro.mdx", "utf-8");
    const mdxSource = await serialize(mdxText);
    return { props: { mdxSource } };
};

export { getStaticProps };

export default RemoteMdxPage;
solved by doing this I guess? the docs don't seem to mention that but if it works it works
View full answer

1 Reply

RexOP
import { readFile } from "fs/promises";
import { serialize } from "next-mdx-remote/serialize";
import { MDXRemote, MDXRemoteSerializeResult } from "next-mdx-remote";
import { useMDXComponents as useCustomMdxComponents } from "../../mdx-components.tsx";
import { useMDXComponents } from "@mdx-js/react";

interface Props {
    mdxSource: MDXRemoteSerializeResult;
}

const RemoteMdxPage = ({ mdxSource }: Props) => {
    const baseComponents = useMDXComponents();
    const components = useCustomMdxComponents(baseComponents);

    return <MDXRemote {...mdxSource} components={components}  />;
};

const getStaticProps = async () => {
    const mdxText = await readFile("public/docs/docs/Intro.mdx", "utf-8");
    const mdxSource = await serialize(mdxText);
    return { props: { mdxSource } };
};

export { getStaticProps };

export default RemoteMdxPage;
solved by doing this I guess? the docs don't seem to mention that but if it works it works
Answer