Commenting in JSX

Abstract image used to represent Commenting in JSX
Image by Volodymyr Hryshchenko.

JSX does not accept HTML comment syntax, delimited by <!-- and -->. To leave a comment inside JSX, use a JavaScript block comment wrapped in curly braces:

{/*
  This is a comment block
*/}

This is just a bogstandard JavaScript block comment inside of curly braces, which lets the parser know to interpret the contents (e.g., a comment block) as JavaScript rather than a string. It is worth mentioning that because JSX is encapsulated markup, inline comments (that start with //) do not work in the same way.

All of this is very useful if you want to leave comments in your code for other developers to see, but what it does not do is output actual HTML comments into the markup. Although admittedly, the use case is slim, I've recently come across this need myself: HTML comments were needed to mark out a section of the DOM for an illadvised thirdparty plugin to target. Why the developers wanted HTML comments rather than something like a classname or ID, I'm not sure; but there we go!

Photograph of metal frames on an orange and blue background by Lea L on Unsplash.

The conditionalcomment markup below is a legacy illustration, not a general way to detect Internet Explorer in React. Conditional comments belong to the older IE document modes that support them; IE 10 standards mode and modern browsers treat this downlevelhidden form as an ordinary comment. Check the actual browser and document mode before relying on it.

For that unusual plugin requirement, I used dangerouslySetInnerHTML:

<div
  dangerouslySetInnerHTML={{
    __html: `
    <!--[if IE]>
      <p>Content for a supported legacy IE document mode</p>
    <![endif]-->
  `,
  }}
/>;

The main disadvantage to this is that you will also get a random <div> in your markup, although for the very limited use cases where this might be useful, I've not found that to be an issue:

<div>
  <!--[if IE]>
    <p>Content for a supported legacy IE document mode</p>
  <![endif]-->
</div>

One quick note on the difference between using dangerouslySetInnerHTML versus innerHTML which at first glance would also make a suitable solution.

With dangerouslySetInnerHTML, React sets the element's raw HTML rather than managing its contents as normal JSX children. React still manages the containing element, and changing the __html value can replace its contents. Writing innerHTML directly can conflict with later React updates. Use only HTML you trust or have sanitised; this API does not escape it for you.


Want to find out more?

If you need senior handson support with a complex React or Next.js platform, migration, performance issue, or technical SEO problem, send me the context and I'll tell you where I can help.