Languages
[Edit]
EN

React - create HTML comment (<!-- comment -->)

7 points
Created by:
Isaiah89
721

In this short article, we would like to show how to create HTML comment from JSX syntax in React.

Quick solution:

 

Practical examples

Edit

1. Reference based solution

Edit

In this section, you can find solution that injects comment using React reference and outerHTML DOM property.

Advantages:

  • creates pure comment node

Disadvantages:

  • doesn't work in SSR mode (server returns just empty <script type="text/placeholder"></script> element that in the next step is rendered in the web browser as comment node),
  • it is required to escape special characters by self from text prop.

Generated source code preview:

HTML comment created from JSX in React.
HTML comment created from JSX in React.

 

2. Property based solution

Edit

In this section, you can find solution that injects comment using dangerouslySetInnerHTML React property.

Advantages:

  • works in SSR mode

Disadvantages:

  • uses additional wrapping HTML element (comment is located inside <span></span> element),
  • it is required to escape special characters by self from text prop.

Generated source code preview:

HTML comment created from JSX in React.
HTML comment created from JSX in React.

 

3. Mixed solution

Edit

In this section, you can find solution that injects comment togather using dangerouslySetInnerHTML React property and React references and outerHTML DOM property.

Advantages:

  • works in SSR mode,
  • finally creates pure comment node.

Disadvantages:

  • comment returned from server differs than rendered in the web browser what finally is accepted.
  • it is required to escape special characters by self from text prop.

 

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join