-
Notifications
You must be signed in to change notification settings - Fork 3
/
HTMLComment.jsx
44 lines (37 loc) · 941 Bytes
/
HTMLComment.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import React from 'react';
import { useLayoutEffect } from '../utils/useIsomorphicLayoutEffect'
import PropTypes from 'prop-types';
/**
* @param {{text: string}} props
*/
const HTMLComment = (props) => {
const { text } = props;
const ref = React.createRef();
useLayoutEffect(() => {
let el = null
let parent = null
let comm = null
if (ref.current) {
el = ref.current;
parent = el.parentNode;
comm = (window || global).document.createComment(` ${text.trim()} `);
try {
if (parent && parent.contains(el)) {
parent.replaceChild(comm, el);
}
} catch (err) {
console.error(err);
}
}
return () => {
if(parent && el && comm) {
parent.replaceChild(el, comm)
}
}
}, []);
return <span ref={ref} style={{ display: 'none' }} />;
};
HTMLComment.propTypes = {
text: PropTypes.string,
};
export default HTMLComment;