#How to Render mdx file content

10 messages · Page 1 of 1 (latest)

empty scarab
#

We're fetching the content of our MDX file from the database, presented as a string. How can we display that content as HTML(Render) within slug.astro?

neon fiber
#

To render markdown pulled from a database, you'll have to setup your own rendering pipeline. One drawback to this is you won't be able to render Astro functions in your MDX (at the moment Astro components can't be rendered outside an Astro build).

You can use unified's remark & rehype with the MDX plugin for remark along with any plugins you need. Once you render the output AST to HTML (here's a good recipe), you can use <Fragment set:html={myOutputHTML}> to use the output in your component

pastel hatch
#

@neon fiber wouldn't that depend on whether he's using SSG or not? Because in getStaticPaths() he could fetch the MDX from the db and render it at build time.

neon fiber
#

yep. the question is tagged with SSR, so I'm guessing that's the rendering mode. also, Astro doesn't expose it's MDX rendering, so there's no way to take that string, and render it the same way as e.g. content collections, which would allow .astro components to be used, etc.

pastel hatch
#

Gotcha, thanks! Missed the tag completely.

barren grail
# neon fiber To render markdown pulled from a database, you'll have to setup your own renderi...

I confirm this as current status so to say, I managed nevertheless recently to rended MD not MDX using Astro components with a custom pipeline that does not depend on vite and works in SSR. It could get packed better but already functional
https://github.com/MicroWebStacks/astro-big-doc, so I added it to my Astro Theme. MDX is probably the hardest and last thing that could shift to SSR due to its potential code imports mix with content, so you'd have to embed vite in SSR before.

empty scarab
#

@neon fiber Thank you very much. I am able to partially achieved the mdx rendering process. But i have some issues like in my mdx file there are some dynamic content like calling queries and displaying result.
below is the sample code.

import QueryResult from "../../../components/native/QueryResult/QueryResult.astro";

<QueryResult
 title="Awareness Training"
 gridStyle="aggrid-default"
 connection="testdb"
 language="postgres"
 >
 {`SELECT * from table`}
</QueryResult>

How to render this dynamic content from the component and display the query result in the page ?

sage turret
#

Yes, I have same issue while I am using direct HTML tags in MDX like <img src="sample.png" /> . It just prints those tag as string format.

empty scarab
neon fiber
#

Like I mentioned above, there's currently no way to render .astro components in MDX outside of the builtin method. You could try implementing other UI frameworks, but for now there's no way to add .astro components