Reputation: 851
I am trying to render an html component that has a comment it so that the comment shows up in the DOM as comment.
I currently have
<head>
<title>{props.pageTitle}</title>
</head>
But I would like to have
<head>
<title>{props.pageTitle}</title>
<!-- Some information here -->
</head>
And I would like to avoid using the following:
dangerouslySetHtml
element.innerHTML = "...";
element.outerHTML = "...";
Upvotes: 0
Views: 1154
Reputation: 36
I found a way to insert comments almost instantly and without wrappers, but it only works when rendered from the server side (see this answer), so it doesn't update its state on the client.
If you need to insert some info for humans to read (such as debug metadata, or easter eggs), this should be good enough. But, if your HTML is post-processed by something that doesn't run scripts from the document, it will only see a <script>
tag with the code instead.
"use client";
export default function Comment({ text }) {
if (typeof window === "undefined") {
const code = `document.currentScript.outerHTML = "<!-- ${text} -->"`;
return <script>{code}</script>;
}
}
Upvotes: 0
Reputation: 29
Once the component mounted, you could retrieve the current DOM element and, then apply some DOM operations to place the HTML comment wherever you need. You can find below an example of a component wrapped by HTML comments.
componentDidMount() {
// Get current node
let currentNode = ReactDOM.findDOMNode(this);
// Get parent node
let parentNode = currentNode.parentNode;
// Create the comment to insert before
let commentBefore = document.createComment("Begin Tag");
parentNode.insertBefore(commentBefore, currentNode);
// Create the comment to insert after
let commentAfter = document.createComment("End Tag");
parentNode.insertBefore(commentAfter, currentNode.nextSibling);
}
Upvotes: 2