Passing custom components after evaluate #1929
-
Hi there, great library first of all. I'm trying to create a React component which takes in a string of mdx, evaluate it, then render it, with custom components. I'm having difficulty properly passing in my custom component, this is what I've tried: const mdxString = `
# hi
<Foo />
` import { compile, evaluate } from "@mdx-js/mdx"
import React, { useEffect, useState } from "react"
import * as runtime from "react/jsx-runtime"
const components = {
Foo: () => <div>Nice</div>,
}
type MdxRendererProps = {
mdx: string
}
const MdxRenderer: React.FC<MdxRendererProps> = ({ mdx }) => {
// MDXContent
const [Content, setContent] = useState<any>(undefined)
useEffect(() => {
const c = async () => {
const compiled = await compile(mdx)
console.log(compiled)
const { default: Content } = await evaluate(mdx, {
Fragment: undefined,
jsx: undefined,
jsxs: undefined,
...runtime,
})
console.log("evaluated Content", Content)
setContent(Content)
}
c()
}, [mdx])
return Content
? Content({ components })
: null
} With this, I'm just getting the error:
Any suggestions on what I might be missing to pass down my custom components? Edit: I just found about the hooks approach from the CRA demo, looking into it now ... Edit 2: Looks like the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Using the hooks approach described as the CRA demo, this works import { evaluate } from "@mdx-js/mdx"
import { useEffect, useState } from "react"
import * as runtime from "react/jsx-runtime"
type UseMdxProps = {
mdx: string
}
export const useMdx = ({ mdx }: UseMdxProps) => {
// Should be typed as MDXModule
const [exports, setExports] = useState<any>(undefined)
useEffect(() => {
evaluate(mdx, {
Fragment: undefined,
jsx: undefined,
jsxs: undefined,
...runtime,
}).then((exports) => setExports(exports))
}, [mdx])
return exports
} import React from "react"
import { useMdx } from "./useMdx"
const components = {
Foo: () => <div>Nice</div>,
}
type MdxRendererProps = {
mdx: string
}
export const MdxRenderer: React.FC<MdxRendererProps> = ({ mdx }) => {
const exports = useMdx({ mdx })
const Content = exports?.default
return Content
? Content({ components })
: null
} |
Beta Was this translation helpful? Give feedback.
Using the hooks approach described as the CRA demo, this works