Marcelo Carmona
Published on

How to Comment in React, JSX, and TSX

Authors

If you searched for react comment, jsx comments, reactjs comment, or how to comment in TSX, the answer is the same: inside JSX or TSX you need to use JavaScript comments wrapped in curly braces.

How to comment in React JSX

It is not possible to use HTML comments inside JSX because JSX is JavaScript syntax that compiles to JavaScript function calls.

function Example() {
  return (
    <div>
      <!-- This does not work -->
      <p>Hello</p>
    </div>
  )
}

To write a React comment inside JSX, use a JavaScript block comment inside curly braces:

function Example() {
  return (
    <div>
      {/* This works */}
      <p>Hello</p>
    </div>
  )
}

Single-line JSX comments

Use the same syntax even for a single-line JSX comment:

return (
  <section>
    {/* Rendered only when the user is logged in */}
    <Dashboard />
  </section>
)

Multi-line React comments

React comments can also span multiple lines:

return (
  <section>
    {/*
      Explain why this branch exists,
      or temporarily describe the UI below.
    */}
    <Dashboard />
  </section>
)

How to comment out React code

If you want to comment out React code or temporarily disable a component, wrap the JSX in a comment:

return (
  <main>
    {/* <Sidebar /> */}
    <Content />
  </main>
)

For a larger block:

return (
  <main>
    {/*
    <Sidebar />
    <Filters />
    <Recommendations />
    */}
    <Content />
  </main>
)

How to comment in TSX

TSX uses the same comment syntax as JSX. If you are writing React with TypeScript, use curly braces plus a JavaScript block comment:

type Props = {
  title: string
}

export function Header({ title }: Props) {
  return (
    <header>
      {/* TSX comment */}
      <h1>{title}</h1>
    </header>
  )
}

Common mistakes

The most common mistake is trying to use HTML comments inside JSX:

<!-- Wrong inside JSX -->

Another common mistake is trying to use // directly inside JSX markup:

return (
  <div>
    // Wrong inside JSX
    <p>Hello</p>
  </div>
)

// works in regular JavaScript outside the returned JSX, but not directly inside the markup:

// This is fine
const title = 'Hello'

return <h1>{title}</h1>

Quick answer

  • React comments inside JSX: {/* comment */}
  • JSX comments: {/* comment */}
  • TSX comments: {/* comment */}
  • Comment out React code: {/* <Component /> */}

Related React articles