21

Is there a way to insert an HTML comment node in React JSX, in the same way you might insert a component or DOM node?

E.g., something like:

React.createElement(Comment, {}, "comment text");

Would render to:

<!-- comment text -->

The idea is that the comment be visible on the page, so { /* this /* } doesn't answer my question.

Note that the following related question doesn't have an answer and asks for something somewhat different:

How to render a HTML comment in React?

I just want to render a single comment node. I notice that React infrastructure renders HTML comments on its own, so perhaps there is a (slightly hacky?) way to do it too.

Community
  • 1
  • 1
GregRos
  • 8,036
  • 3
  • 32
  • 60
  • 1
    I think it is not possible at the moment due to not being able to uniquely identify comment nodes in the dom. Best reference I could find: https://groups.google.com/forum/#!topic/reactjs/y7AGHSntR8I – Davin Tryon Nov 02 '16 at 14:19
  • 1
    This particular answer answers your question https://stackoverflow.com/a/41131326/4373305 – Alex Zinkevych Nov 20 '17 at 10:10
  • @АлексейЗинкевич Thanks! Does that solution have any weird side-effects that you know? – GregRos Nov 20 '17 at 13:35

2 Answers2

5

Another alternative is to use dangerouslySetInnerHTML

<div dangerouslySetInnerHTML={{ __html: '<!-- comment text -->' }} />

dangerouslySetInnerHTML is React's replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it's easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it's dangerous.

https://facebook.github.io/react/docs/dom-elements.html#dangerouslysetinnerhtml

ptim
  • 13,723
  • 9
  • 79
  • 94
  • 9
    Unfortunately this requires a wrapper (in this case: `div`) which may not be ok. React Fragment do not work either since they do not support the `dangerouslySetInnerHTML` attribute yet. – Iso Apr 12 '18 at 10:36
4

Only thing I could think of would be to manipulate the DOM on componentDidMount and add your comment there, but then React wouldn't be handling that DOM manipulation so it might cause some issues?

    var HTMLComment = React.createClass({

      componentDidMount: function(){
        var htmlComment = "<!--" + this.props.comment + "-->"; 
          this.span.innerHTML = htmlComment;
      },

      render: function(){
        return (
            <span ref={(span) => this.span = span} ></span>
        )
      }
    })
StackOverMySoul
  • 1,817
  • 1
  • 11
  • 21