How to comment in React JSX

Getting started with React, you may probably tried to comment some code as every normal sane developer should do, to don't write again or forget a piece of code. React uses JSX, it is a XML-like syntax extension to ECMAScript without any defined semantics. It's NOT intended to be implemented by engines or browsers.

Well, other crazy language with XML syntax, then the comment should be similar to XML, right? However you may be probably surprised, that you can't coment react the JSX area as you do with XML:

import React, {Component} from 'react';

class Main extends Component {
  constructor(props, context) {
    super(props, context);
    // But this will be commented properly because it's Javascript :) not JSX
  }
 
  render() {
    return (
        <div>
            <!-- This won't work -->
            <!-- <span></span>-->
            <!--
            Neither this
            -->
        </div>
    );
  }
}

export default Main;

However, the Javascript can still be commented as usual. How do I comment the JSX area properly?

Commenting JSX

You can't just use HTML comments inside of JSX because the compiler will think that they are real DOM Nodes. To comment properly in JSX, you will comment as you used to do with code blocks in javascript /* Some JS Code */, however the comment needs to be wrapped in curly braces:

import React, {Component} from 'react';

class Main extends Component {
  constructor(props, context) {
    super(props, context);
    /* 
        alert("Hello World");
    */

    // console.log("hey");
  }
 
  render() {
    return (
        {/* A JSX comment, this will work :)
        <div>
        
        </div>
        */}
    );
  }
}

export default Main;

As JSX is a "recent" language, pitifully, most of the code editors and IDE doesn't provide shortcuts with the keyboard to comment JSX.

Happy coding !

Become a more social person