Skip to content

Instantly share code, notes, and snippets.

@JonathonRichardson
Created December 12, 2020 18:15
Show Gist options
  • Save JonathonRichardson/f38be1add30a3d5fee915f7961db4fc2 to your computer and use it in GitHub Desktop.
Save JonathonRichardson/f38be1add30a3d5fee915f7961db4fc2 to your computer and use it in GitHub Desktop.
Code for Stack Overflow To Answer Question https://stackoverflow.com/q/40015336/4339894
import * as React from 'react';
import * as ReactDOM from 'react-dom';
interface IProps {
text: string;
}
export class HTMLComment extends React.Component<IProps> {
private node: Comment;
private ref$rootDiv = React.createRef<HTMLDivElement>();
constructor(props: IProps) {
super(props);
this.node = window.document.createComment(props.text);
}
componentDidMount() {
if (this.ref$rootDiv && this.ref$rootDiv.current) {
let divElement = this.ref$rootDiv.current;
// Tell React not to update/control this node
ReactDOM.unmountComponentAtNode(divElement);
// Replace the div with our comment node
this.ref$rootDiv.current.replaceWith(this.node);
}
}
componentDidUpdate(prevProps: IProps) {
if (prevProps.text !== this.props.text) {
this.node.textContent = this.props.text;
}
}
componentWillUnmount() {
this.node.remove();
}
render() {
return (
<div
ref={this.ref$rootDiv}
style={{
display: 'none',
}}
/>
);
}
}
interface IHTMLCommentWrapperProps {
}
const HTMLCommentWrapper: React.FunctionComponent<IHTMLCommentWrapperProps> = (props) => {
return (
<React.Fragment>
<HTMLComment text={`<fragment data-reactid="">`} />
{props.children}
<HTMLComment text={`</fragment>`} />
</React.Fragment>
)
}
declare global {
namespace JSX {
interface IntrinsicElements {
'c': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
'd': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
'e': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>;
}
}
}
const A: React.FunctionComponent = (props) => { return <a>{props.children}</a> }
const B: React.FunctionComponent = (props) => { return <b>{props.children}</b> }
const C: React.FunctionComponent = (props) => { return <c>{props.children}</c> }
const D: React.FunctionComponent = (props) => { return <d>{props.children}</d> }
const E: React.FunctionComponent = (props) => { return <e>{props.children}</e> }
const App: React.FunctionComponent = () => {
return (
<A>
<B></B>
<HTMLCommentWrapper>
<C></C>
<D></D>
</HTMLCommentWrapper>
<E></E>
</A>
)
}
let el$root = document.getElementById('react-app');
if (el$root) {
ReactDOM.render(<App />, el$root);
}
@JonathonRichardson
Copy link
Author

You can see this compiled using the typescript playground.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment