First I tried the normal ways, like using html-to-react and the alike, but somehow due to some finicky formatting of strings, this library just flat out refuses 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:
- Convert HTML into Markdown, with turndown
- 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 life 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.