Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert HTML comments in React

Tags:

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.

like image 233
GregRos Avatar asked Nov 02 '16 14:11

GregRos


People also ask

How do you add a comment to a React in HTML?

We can write comments in React using the double forward-slash // or the asterisk format /* */, similar to regular JavaScript.

How do you add comments in JSX?

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.

Can we use HTML tags in react JS?

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.

Can we write HTML in React?

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.


1 Answers

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

like image 51
ptim Avatar answered Oct 02 '22 18:10

ptim