EN
React - create HTML comment (<!-- comment -->)
7 points
In this short article, we would like to show how to create HTML comment from JSX syntax in React.
Quick solution:
xxxxxxxxxx
1
const HtmlComment = ({text}) => {
2
const html = `<!-- ${text} -->`;
3
const callback = (instance) => {
4
if (instance) {
5
instance.outerHTML = html;
6
}
7
};
8
return (<script ref={callback} type="text/comment" dangerouslySetInnerHTML={{__html: html}} />);
9
};
10
11
// Usage: <HtmlComment text="Some HTML comment here ..." />
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.
xxxxxxxxxx
1
import React, {useRef, useEffect} from 'react';
2
3
const HtmlComment = ({text}) => {
4
const ref = useRef();
5
useEffect(() => {
6
ref.current.outerHTML = `<!--${text}-->`;
7
}, [text]);
8
return (<script ref={ref} type="text/placeholder" />);
9
};
10
11
12
// Usage example:
13
14
const App = () => {
15
return (
16
<div>
17
<HtmlComment text="Some HTML comment here ..." />
18
</div>
19
);
20
};
21
22
export default App;
Generated source code preview:

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.
xxxxxxxxxx
1
import React from 'react';
2
3
const HtmlComment = ({text}) => {
4
return (<span dangerouslySetInnerHTML={{__html: `<!-- ${text} -->`}} />);
5
};
6
7
8
// Usage example:
9
10
const App = () => {
11
return (
12
<div>
13
<HtmlComment text="Some HTML comment here ..." />
14
</div>
15
);
16
};
17
18
export default App;
Generated source code preview:

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.
xxxxxxxxxx
1
import React from 'react';
2
3
const HtmlComment = ({text}) => {
4
const html = `<!-- ${text} -->`;
5
const callback = (instance) => {
6
if (instance) {
7
instance.outerHTML = html;
8
}
9
};
10
return (<script ref={callback} type="text/comment" dangerouslySetInnerHTML={{__html: html}} />);
11
};
12
13
14
// Usage example:
15
16
const App = () => {
17
return (
18
<div>
19
<HtmlComment text="Some HTML comment here ..." />
20
</div>
21
);
22
};
23
24
export default App;