How to render a HTML comment in React?

Sometimes, we want to render a HTML comment in React.

In this article, we’ll look at how to render a HTML comment in React

How to render a HTML comment in React?

To render a HTML comment in React, we can use the dangerouslySetInnerHTML prop.

For instance, we write:

import React from "react";

const ReactComment = ({ text }) => {
  return <div dangerouslySetInnerHTML={{ __html: `<!-- ${text} -->` }} />;
};

export default function App() {
  return <ReactComment text={"My beautiful HTML comment"} />;
}

We set dangerouslySetInnerHTML to an object that has the __html property set to a string with the HTML comment.

Then we should see the comment when we inspect the HTML code in the Elements tab of the dev console of our browser.

Conclusion

To render a HTML comment in React, we can use the dangerouslySetInnerHTML prop.