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="..." />'}</>
Image of my head

About the author

Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.

When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.

If you need help on a project, please reach out and let's work together.

To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.