How to write comments in React and JSX

Writing comments in React components can be done just like how you comment in regular JavaScript classes and functions. You can use the double forward-slash syntax // to comment any code:

function App() {

  // const name = "John"
  // const age = 28

  return (
    <h1>My Application</h1>
  );
}

Or you can use the forward-slash and asterisk format /* */ like this:

function App() {

  /*
  const handleClick = () => {
    console.log('this function is called')
  }
  */

  return (
    <h1>My Application</h1>
  );
}

Generally, the forward-slash and asterisk format for comments is used for writing real comments like license and other documentation for developers to read instead of commenting out code:

/** @license React v16.13.1
 * react.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

But there is no strict rule that says you can’t use it for commenting out code too.

Writing comments in React JSX

Commenting inside React JSX syntax is a bit confusing because while JSX gets rendered just like normal HTML by the browser, JSX is actually an enhanced JavaScript that allows you to write HTML in React.

You can’t write comments as you might do in HTML and XML with <!-- --> syntax. The following example will throw Unexpected token error:

export default function App() {
  return (
    <div>
      <h1>Hello World~ </h1>
      <!-- <p>My name is Bob</p> -->
      <p>Nice to meet you!</p>
    </div>
  );
}

To write comments in JSX, you need to use JavaScript’s forward-slash and asterisk syntax, enclosed inside a curly brace {/* comment here */}.

Here’s the example:

export default function App() {
  return (
    <div>
      <h1>Commenting in React and JSX~ </h1>
      {/* <p>My name is Bob</p> */}
      <p>Nice to meet you!</p>
    </div>
  );
}

And here’s for multiple lines of JSX:

export default function App() {
  return (
    <div>
      {/* <h1>Commenting in React and JSX~ </h1>
      <p>My name is Bob</p>
      <p>Nice to meet you!</p> */}
    </div>
  );
}

It may seem very annoying that you need to remember two different ways of commenting when writing React code. But don’t worry!

Most modern IDEs like VSCode and CodeSandbox already know about this issue. They will write the right comment syntax for you automatically when you press on the comment shortcut CTRL+/ or ⌘+/ for macOS.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.