iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📝

How to Write Comments in React JSX

に公開

While implementing the frontend in Next.js, I wasn't sure how to write comments within JSX, so I'm making a note of it here.

Single-line comments

hello.tsx
return (
    <div>
      {/* Single-line comment */}
      Hello world!
      {
        // Single-line comment
      }
    <div>
)
Error: 
  x Unexpected token `div`. Expected jsx identifier
    ,-[hello.tsx:17:1]
 17 |   return (
 18 |     <div>
    :      ^^^
 19 |       {/* Single-line comment */}
 20 |       Hello world!
 21 |       { // Single-line comment}
    `----

Caused by:
    Syntax Error

Multi-line comments

hello.tsx
return (
    <div>
    {/* Multi-line comments
    can be written
    with line breaks */}
    Hello world!
    {
        // You can also
        // write single-line comments
        // on multiple lines
    }
    </div>
)

Since // requires attention to potential syntax errors, it's generally better to use /* */ even for single-line comments unless there's a specific reason not to.

References

https://legacy.reactjs.org/docs/faq-build.html#how-can-i-write-comments-in-jsx
https://www.delftstack.com/howto/react/comments-in-react/

Discussion