InsertAfter's Logo

Print your Markdown content with React through AST

If you ever used Contentful, the head-less CMS, chances are that, like I did, you ended up creating some code to map your contentful blocks to your React components.

I found out this approach really neat, but for my own blog, I didn't want to use anything else then Markdown files committed in my repository.

Get a tree from your Markdown 🔗

The first thing I start looking for is to have a tree from my Markdown files, preferably, something resembling the Contenful block tree.

I found out that by combining the unified and remark modules, you end up with something that really looks like the Contenful data.

Dealing with HTML 🔗

The hard part were to deal with the HTML markup. Indeed, it wasn't parsed taking in count the start and end of the elements. I had to create a recursive algorithm to wrap it up altogether in something meaningful. I still have to parse the HTML attributes to have something usable for most use cases.

Finally, mapping to elements 🔗

The final rendering function is pretty similar to the Contenful one. Never use the dangerouslySetInnerHTML method again ;).

Neat things 🔗

Additionally, I managed to make of all my <h2+> titles to have anchors automatically generated so that one can link to a particular section easily (like here with the "Une fuite en avant sans vision politique" title).

I just had to create a function that retrieve the title text whatever its contents and its depth. And add my anchor component to the element mapper.

I hope you will enjoy the code, feel free to reuse parts of it in your own repos. I'll make a library of it once I get something stable and reusable.

Published at mercredi 1 décembre 2021 à 23:00:00.