Skip to content

Instantly share code, notes, and snippets.

@maestrow
Last active February 22, 2023 16:57
Show Gist options
  • Save maestrow/66aea1a6e89586f450af13bfdc87add6 to your computer and use it in GitHub Desktop.
Save maestrow/66aea1a6e89586f450af13bfdc87add6 to your computer and use it in GitHub Desktop.
How to use html tags in markdown with remark-parse?

How to use html tags in markdown with remark-parse?

From documentation: Note that toHast.allowDangerousHTML does not work: it’s not possible to inject raw HTML with this plugin (as it’s mean to prevent having to use dangerouslySetInnerHTML).

But still there is a way to allow html tags. Thanks to ChristianMurphy suggestion.

I've made just couple improvements:

  1. Module rehype-dom-parse leads to error: 'document is not defined'. So I replace it with 'rehype-parse'.
  2. Extract rehypeParser from handler, so it's created only once.
  3. Also notice about sanitize: false
var unified = require('unified')
var remark = require('remark-parse')
var remark2react = require('remark-react');
var ReactDOMServer = require('react-dom/server');
var rehype = require('rehype-parse')

const sample = `
markdown is here
<div style="color:gray;">
text <a href="#">link</a>
</div>
`

const rehypeParser = unified().use(rehype, { fragment: true });

const parser = unified()
  .use(remark)
  .use(remark2react, {
    toHast: {
      handlers: {
        html: (h, node) => 
          // process raw HTML text into HAST so react remark can process it
          rehypeParser.parse(node.value).children
      }
    },
    sanitize: false
  });

const result = parser.processSync(sample)
const html = ReactDOMServer.renderToStaticMarkup(result.contents)
console.log(html)

output:

<p>markdown is here</p>
<div style="color:gray">
text <a href="#">link</a>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment