Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The reason for the error from Babel is that JSX is an HTML like (more so XML) syntax, not HTML. The obtuse comment syntax is because you need to escape to JavaScript with the braces, then use a multi-line JavaScript comment block. I wish they would've allowed HTML comments in the original design, but my guess is that comments were an oversight that just happened to work due to the escape syntax.


One good reason not to support it is that it’s ambiguous: is it a comment (to be ignored), or does it represent a comment node? If the former, why not just use //? If the latter, it requires that the library or compilation target or whatever support comment nodes, which is more work for a dubious feature.


I'd argue that comments only serve to help the developer. And when using JSX, the generated HTML might not look pretty (such as being a single, long line). So an HTML style comment in the JSX should be stripped because debugging the minified HTML isn't something people generally do.

And if, for some reason, you wanted to inject an HTML comment into the output, you could abuse the `dangerouslySetInnerHTML` prop like this:

    function Comment(props)
    {
        return <span dangerouslySetInnerHTML={{__html: `<!-- ${props.comment} -->` }} />;
    }
Then use it like this:

    ...
    <Comment comment="my comment" />
    ...
Using `React.Fragment` doesn't work, sadly. Use the "Inspect Element" tool on the output here: https://playcode.io/870223


There are other use cases for (preserved) HTML comments in (or produced by) JSX, but generally more for library authors than end users. For example, comments can be used for hydration markers to delineate “hydration islands” without need for a wrapping element. (I have a proof of concept of this sitting in a Codepen somewhere.)

And while it doesn’t work in React’s Fragment, it can certainly work with another compiler. JSX doesn’t specify anything about what it compiles to, React.createElement/_jsx are just defaults.


It shouldn't be hard to create a component that does what you want

<Comment>some comment</Comment>




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: