React Reference ยท JSX Syntax and Rules
Comments in JSX
How to write comments in React JSX: the curly-brace block comment for children, normal comments inside tags and attributes, and what never to put in them.
JSX looks like HTML, but <!-- --> comments do not work in it. Anything between tags is either literal text or a JavaScript expression in curly braces, so a comment there has to be a JavaScript comment inside braces: {/* like this */}. The braces open an expression, and the comment is the whole expression, which produces nothing.
Inside a tag's attribute list, and everywhere that is plain JavaScript (above the return, inside functions), ordinary // and /* */ comments work without braces.
function Card() { // A normal comment in JavaScript return ( <section> {/* A comment between children */} <h2 // A comment among the attributes className="title" > Hello </h2> </section> ); }
Try it
Syntax
| Where | Form |
|---|---|
| Between children | {/* comment */} |
| Multi-line, between children | {/* line 1 newline line 2 */} |
| Inside a tag, among attributes | // comment on its own line, or /* comment */ |
| Outside the markup (JavaScript) | // comment or /* comment */ |
| Not valid | <!-- comment --> (a syntax error) |
Edge cases: // written directly in text between tags is just text. A {// comment} on one line swallows the closing brace and is a syntax error; use the block form or put the closing brace on its own line.
Usage notes
- Comments never reach the DOM. The compiler removes them, so they cost nothing at runtime and are not visible in the browser's inspector.
- Prefer explaining why. Name components and variables clearly so a comment is needed only for non-obvious reasons.
- To disable markup temporarily, wrap it in
{/* ... */}. Nested block comments inside it will end the comment early, so remove inner*/first. - Do not leave secrets or private notes. The source of your bundle is public; comments are removed from the compiled output only when your build minifies it.
- A line comment before an attribute list works because attributes are inside the tag and parsed as JavaScript-like tokens.
- Editors usually toggle the right comment style for you; check that it chose braces between children.
Related
- JSX expressions, JSX children, JSX elements
- Lessons: JSX basics, JSX in depth