How to render a constant with mdx and inject custom components?

15 views Asked by At

I tried the evaluate function, but I dont know how to pass my custom components

I tried this:

<MDXProvider components={components}>
    <MdxPreview content={selectedNote.content} />
</MDXProvider>

and I defined my components like this:

const components = {
  h1: H1,
  Collapsible: Collapsible,
};

This is how I use the evaluate method:

// MdxPreview
import React, { useEffect, useState } from "react";
import { evaluate } from "@mdx-js/mdx";
import * as runtime from "react/jsx-runtime";

type MdxPreviewProps = { content: string };
export const MdxPreview = ({ content }: MdxPreviewProps) => {
  const exports = useMDX(content);
  const Content = exports.default;
  return <Content />;
};

function useMDX(content: string) {
  const [exports, setExports] = useState({ default: runtime.Fragment });

  useEffect(() => {
    evaluate(content, { ...(runtime as any) }).then((exports) =>
      setExports(exports as any)
    );
  }, [content]);

  return exports;
}

Finally this is my mdx value on selectedNote.content

<Collapsible title="My title here">
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Exercitationem
</Collapsible>
0

There are 0 answers