Commenting in JSX

Hero image for Commenting in JSX. Image by Volodymyr Hryshchenko.
Hero image for 'Commenting in JSX.' Image by Volodymyr Hryshchenko.

React does not support HTML comment nodes (in between <! and >), as it is unable to uniquely identify them within the DOM. If you are reading this, then you are likely already familiar with JSX comments, which look like this:

{/*  This is a comment block*/}

This is just a blogstandard 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.

In theory, you may also need this type of approach if combining your React development with oldfashioned Internet Explorer conditionals. There are plenty of other (better) ways to target Internet Explorer within React, but this is another use case I've seen being discussed.

The only reliable, novel approach I've been able to find has been to use dangerouslySetInnerHTML:

<div  dangerouslySetInnerHTML={{    __html: `    <!--[if IE]>      <p>Internet Explorer will still render this text</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>Internet Explorer will still render this text</p>  <![endif]--></div>

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

When using dangerouslySetInnerHTML, you signal to React that the contents of that particular element is not something it needs to care about. When it goes to compare the virtual DOM against the actual DOM, it will therefore altogether bypass the node whereas if you use innerHTML, there is a risk that React will overwrite the comment you have manually placed in there, in favour of what React has stored in the virtual DOM.


Categories:

  1. Development
  2. Front‑End Development
  3. HTML
  4. JavaScript
  5. JSX
  6. React