Last active
September 5, 2022 17:35
-
-
Save alexeychikk/bfe72a072a9a962f2da900b6151e4aae to your computer and use it in GitHub Desktop.
Simple React HTML comment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Usage (I however think that the code is self explanatory) | |
| <ReactComment text={` | |
| Very long comment with html link | |
| <a href="https://gist.github.com/alexeychikk/bfe72a072a9a962f2da900b6151e4aae">Star me :)</a> | |
| `} /> | |
| */ | |
| import React, {Component, PropTypes} from 'react'; | |
| import ReactDOM from 'react-dom'; | |
| class ReactComment extends Component { | |
| static propTypes = { | |
| text: PropTypes.string, | |
| trim: PropTypes.bool | |
| }; | |
| static defaultProps = { | |
| trim: true | |
| }; | |
| componentDidMount() { | |
| let el = ReactDOM.findDOMNode(this); | |
| ReactDOM.unmountComponentAtNode(el); | |
| el.outerHTML = this.createComment(); | |
| } | |
| createComment() { | |
| let text = this.props.text; | |
| if (this.props.trim) { | |
| text = text.trim(); | |
| } | |
| return `<!-- ${text} -->`; | |
| } | |
| render() { | |
| return <div />; | |
| } | |
| } | |
| export default ReactComment; |
Author
Just as a note, this does not work when using
renderToStaticMarkupofreact-dom/server, becausecomponentDidMountdoes not get triggered. For reference: facebook/react#16931For me generating comments is required, not only "inside the browser" but when using react as some part of static-file-generation outside of the browser.
@alexeychikk That won't work, as it always creates a wrapper-element
This causes a crash for me when navigating with react-router-dom to a component where ReactComment is not used.
I have made an npm package for this: https://www.npmjs.com/package/react-html-comment
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just as a note, this does not work when using
renderToStaticMarkupofreact-dom/server, becausecomponentDidMountdoes not get triggered. For reference: facebook/react#16931For me generating comments is required, not only "inside the browser" but when using react as some part of static-file-generation outside of the browser.