Max SchmittMS
20th June 2020

How to escape HTML tags with MDX

There are a few ways to escape HTML tags inside MDX content. There is no official documentation that I know of, but I figured out the following methods through trial and error.

If there is a case that I didn't cover, let me know on Twitter and I'll update this article. :)

Escape HTML tags within Markdown content

If the HTML tag is surrounded by other markdown content, you can simply escape the closing angular bracket > with a backslash \.

Example

This is the '<p>' tag
HTML tags can have attributes: <img src="...">
HTML tags can be self-closing: <img src="..." />

Inside a block-quote: <blockquote></blockquote>

  • Anchor tag: <a>
  • Paragraph tag: <p>

mdx

This is the '<p\>' tag
HTML tags can have attributes: <img src="..."\>
HTML tags can be self-closing: <img src="..." /\>
> Inside a block-quote: <blockquote\></blockquote\>

Escape HTML tag on its own line

If you want to show an HTML tag on its own line, just use JSX syntax to render a string:

Example

<img src="...">

<img src="..." />

<img>

<p></p>

mdx

<p>{'<img src="...">'}</p>
<p>{'<img src="..." />'}</p>
<p>{'<img>'}</p>
<p>{'<p></p>'}</p>

Escape HTML tag inside MDX with fragments

In some cases, you need to use a React fragment to escape the tag. I've come across this case for showing HTML tags with attributes inside markdown lists with:

Example

  • <img src="...">
  • <img src="..." />

mdx

- <>{'<img src="...">'}</>
- <>{'<img src="..." />'}</>

Need help on a project?

I'm available for freelance work.
Send me an email! Or find out more about my services.