How to Comment in JSX: Simple Syntax and Examples
In JSX, use curly braces with JavaScript comments inside like
{/* comment here */} to add comments within the markup. For comments outside JSX, use normal JavaScript comments // or /* */.Syntax
To add comments inside JSX, wrap the comment in curly braces and use JavaScript comment syntax inside. This looks like {/* comment text */}. For comments outside JSX, use normal JavaScript comments.
- Inside JSX:
{/* comment */} - Outside JSX:
// commentor/* comment */
jsx
function Example() { return ( <div> {/* This is a JSX comment */} <p>Hello, world!</p> </div> ); } // This is a JavaScript comment outside JSX
Example
This example shows how to add comments inside JSX elements and outside the JSX return statement in a React functional component.
jsx
import React from 'react'; function Greeting() { // This comment is outside JSX return ( <section> {/* This comment is inside JSX and will not appear in the output */} <h1>Welcome to React!</h1> {/* You can comment out elements like this: <p>This paragraph is commented out and won't render.</p> */} </section> ); } export default Greeting;
Output
<section>
<h1>Welcome to React!</h1>
</section>
Common Pitfalls
Common mistakes include trying to use HTML-style comments <!-- comment --> inside JSX, which will cause errors. Also, forgetting the curly braces around the comment inside JSX will break the code.
Remember, JSX comments must be inside {/* */} and not just /* */ alone.
jsx
/* Wrong way inside JSX - causes error */ function Wrong() { return ( <div> {/* This is not valid in JSX */} <p>Oops!</p> </div> ); } /* Correct way */ function Right() { return ( <div> {/* This is a valid JSX comment */} <p>All good!</p> </div> ); }
Quick Reference
| Where | Comment Syntax | Notes |
|---|---|---|
| Inside JSX | {/* comment */} | Must use curly braces and JS comment style |
| Outside JSX | // comment | Normal JS single-line comment |
| Outside JSX | /* comment */ | Normal JS multi-line comment |
| Invalid in JSX | Causes syntax error |
Key Takeaways
Use curly braces with /* */ to comment inside JSX: {/* comment */}.
Use normal JavaScript comments (// or /* */) outside JSX code.
Never use HTML-style comments inside JSX; it causes errors.
Always wrap JSX comments in curly braces to keep syntax valid.
Comments inside JSX do not appear in the rendered output.