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.
We can write comments in React using the double forward-slash // or the asterisk format /* */, similar to regular JavaScript.
Syntax. JSX comments begin and end with curly braces {} . Followed by the opening curly brace is a forward slash and an asterisk. After that is the comment and lastly, an asterisk, a forward slash and the closing curly brace.
JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() and/or appendChild() methods. JSX converts HTML tags into react elements.
By default, React does not permit you to inject HTML in a component, for various reasons including cross-site scripting. However, for some cases like a CMS or WYSIWYG editor, you have to deal with raw HTML. In this guide, you will learn how you can embed raw HTML inside a component.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With