ReactJS

How to Replace HTML Tags with React Components

First I tried the normal ways, like using html-to-react and alike, but somehow due to some finicky formatting of strings, this library just flat out refuse to convert legitimate HTML. On top of that, NextJS was complaining loudly about Prop dangerouslySetInnerHTML did not match.

Time to bring out the big guns.

Namely, to:

  1. Convert HTML into Markdown, with turndown
  2. Render Markdown with React Components, with react-markdown

Why this works:

  • Both of these packages are well worn with the test of time, with 5k+ stars on Github, compared to the rather green html-to-react and its peers, so we don’t run into edge cases any more
  • Both packages can be configured extensively to suit our needs
  • Since HTML was converted into markdown first, we can avoid living a dangerous live by eliminating dangerouslySetInnerHTML

Code is simple too:

import TurndownService from 'turndown'
import ReactMarkdown from 'react-markdown'

const turndown = new TurndownService({ linkStyle: 'referenced' })  // I've found referenced link style works better with react-markdown

...
<ReactMarkdown
  source={turndown(initialHTML)}
  renderers={{ paragraph: Text }}      <-- <Text /> being our fancy react componennt
/>

Problem solved.

Standard

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.