profile
Juan Vega
Software Developer | Writer | Nerd

React.js: Adding comments using JSX

One of the cornerstones of any programming language is the ability to add comments alongside its code. This makes it easier to figure out what the developers thought process was during the time of development.

Unfortunately for React.js developers, finding out how to add comments with JSX can be quite a process. There just isn't an ample amount of information about the topic. Thankfully adding JSX comments is almost identical to the syntax used in CSS.

When adding comments in CSS you use two forward slashes with two asterisks inside of them. Most commonly known as block comments.


              /* This is a comment in CSS  */
            

React.js uses the same syntax, with only a minor addition. You still use the block comment syntax, but instead of allowing it to stand on its own, you will need to surround it with curly braces on either side.


              {/*This a comment in JSX*/}
            

It can be a bit confusing since JSX is an extension of JavaScript and logic would dictate that comments should work the same.

Alas, the followign line of code will give an error if you try to run it.


              {<-- JavaScript Comment -->}
            

Furthermore, it does not appear that the React development team has any plans to integrate the JavaScrpt comment syntax.

For now, the block comments with curly braces are the way to go when adding comments alongside JSX.

Here a full example of how comments work in JSX using one of the offical React code snippets.


              function formatName(user) {
                return user.firstName + ' ' + user.lastName;
              }

              const user = {
                firstName: 'Harper',
                lastName: 'Perez'
              };

              const element = (
              {/*This a comment*/},
              <h1>
              Hello, {formatName(user)}!
              </h1>,
              {/*This another comment*/}
              );

              ReactDOM.render(
              element,
              document.getElementById('root')
              );