352

How can I use comments inside the render method in a React component?

I have the following component:

'use strict';
 var React = require('react'),
   Button = require('./button'),
   UnorderedList = require('./unordered-list');

class Dropdown extends React.Component{
  constructor(props) {
    super(props);
  }
  handleClick() {
    alert('I am click here');
  }

  render() {
    return (
      <div className="dropdown">
        // whenClicked is a property not an event, per se.
        <Button whenClicked={this.handleClick} className="btn-default" title={this.props.title} subTitleClassName="caret"></Button>
        <UnorderedList />
      </div>
    )
  }
}

module.exports = Dropdown;

Enter image description here

My comments are showing up in the UI.

What would be the right approach to apply single and multiple line comments inside a render method of a component?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 34
    Good question with single answer. Do not be fooled by 12 answers! They all talk about the same thing: `{/* JSX comment*/}` – Jack Miller Nov 08 '19 at 10:07
  • 3
    Within React(JSX), you can use `{/* comment here */}`, however for javascript `// comment here` works. So, the answer depends on where you want to comment. – muditrustagii Jan 24 '21 at 04:30
  • Related: *[How to comment in React JSX](https://wesbos.com/react-jsx-comments/)* – Peter Mortensen Oct 27 '21 at 22:29
  • 1
    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. – Islam Alshnawey Jun 14 '22 at 00:37

16 Answers16

468

Within the render method comments are allowed, but in order to use them within JSX, you have to wrap them in braces and use multi-line style comments.

<div className="dropdown">
    {/* whenClicked is a property not an event, per se. */}
    <Button whenClicked={this.handleClick} className="btn-default" title={this.props.title} subTitleClassName="caret"></Button>
    <UnorderedList />
</div>

You can read more about how comments work in JSX here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
  • 2
    I don't know why but it always gives me a feelings of bad code or something wrong in the code. in other words, it seems like commenting isn't adjusting in my code in this way. I'm not sure if I was used of double slashes style `//` commenting – Adil Feb 27 '17 at 07:40
  • 6
    And something like
    {/* comment */} creates error. comment must be in a new line.
    – Amir Shabani Nov 10 '19 at 06:39
  • Do not forget to add the empty tag <>> in case you have only one element in your render function, otherwise the comment will be counted as another element and brake the code. – danb4r Nov 25 '22 at 23:52
67

Here is another approach that allows you to use // to include comments:

return (
  <div>
    <div>
      {
        // Your comment goes in here.
      }
    </div>
    {
      // Note that comments using this style must be wrapped in curly braces!
    }
  </div>
);

The catch here is you cannot include a one-line comment using this approach. For example, this does not work:

{// your comment cannot be like this}

because the closing bracket } is considered to be part of the comment and is thus ignored, which throws an error.

Bart Riordan
  • 436
  • 3
  • 8
  • 23
anandharshan
  • 5,817
  • 4
  • 34
  • 33
33

On the other hand, the following is a valid comment, pulled directly from a working application:

render () {
    return <DeleteResourceButton
            // Confirm
            onDelete = {this.onDelete.bind(this)}
            message = "This file will be deleted from the server."
           />
}

Apparantly, when inside the angle brackets of a JSX element, the // syntax is valid, but the {/**/} is invalid. The following breaks:

render () {
    return <DeleteResourceButton
            {/* Confirm */}
            onDelete = {this.onDelete.bind(this)}
            message = "This file will be deleted from the server."
           />
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
papiro
  • 2,158
  • 1
  • 20
  • 29
25

Besides the other answers, it's also possible to use single line comments just before and after the JSX begines or ends. Here is a complete summary:

Valid

(
  // this is a valid comment
  <div>
    ...
  </div>
  // this is also a valid comment
  /* this is also valid */
)

If we were to use comments inside the JSX rendering logic:

(
  <div>
    {/* <h1>Valid comment</h1> */}
  </div>
)

When declaring props single line comments can be used:

(
  <div
    className="content" /* valid comment */
    onClick={() => {}} // valid comment
  >
    ...
  </div>
)

Invalid

When using single line or multiline comments inside the JSX without wrapping them in { }, the comment will be rendered to the UI:

(
  <div>
    // invalid comment, renders in the UI
  </div>
)
Divyanshu Maithani
  • 13,908
  • 2
  • 36
  • 47
23

According to the official site, these are the two ways:

<div>
  {/* Comment goes here */}
  Hello, {name}!
</div>

Second example:

<div>
    {/* It also works 
    for multi-line comments. */}
    Hello, {name}! 
</div>

Here is the reference: How can I write comments in JSX?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Osv
  • 771
  • 8
  • 7
16

To summarize, JSX doesn't support comments, either html-like or js-like:

<div>
    /* This will be rendered as text */
    // as well as this
    <!-- While this will cause compilation failure -->
</div>

and the only way to add comments "in" JSX is actually to escape into JS and comment in there:

<div>
    {/* This won't be rendered */}
    {// just be sure that your closing bracket is out of comment
    }
</div>

if you don't want to make some nonsense like

<div style={{display:'none'}}>
    actually, there are other stupid ways to add "comments"
    but cluttering your DOM is not a good idea
</div>

Finally, if you do want to create a comment node via React, you have to go much fancier, check out this answer.

YakovL
  • 7,557
  • 12
  • 62
  • 102
15

Two ways to add comments in React Native

  1. // (double forward slash) is used to comment only a single line in React Native code, but it can only be used outside of the render block. If you want to comment in a render block where we use JSX, you need to use the second method.

  2. If you want to comment on something in JSX you need to use JavaScript comments inside of curly braces like {/* Comment here /}. It is a regular / Block comment */, but it needs to be wrapped in curly braces.

Shortcut keys for /* Block comments */:

  • Ctrl + / on Windows and Linux.

  • Cmd + / on macOS.

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
  • hi Ramesh R can you make sure when you're doing code edits that you don't mess up the indentation - like this https://stackoverflow.com/revisions/57358471/3 ? thanks –  Aug 07 '19 at 04:48
  • Related: *[We're switching to CommonMark](https://meta.stackexchange.com/questions/348746/)* (2020-06-01) - *"Headlines: Moving forward, you have to add a space after the leading # characters"* – Peter Mortensen Oct 30 '21 at 23:33
14

This is how.

Valid:

...
render() {

  return (
    <p>
       {/* This is a comment, one line */}

       {// This is a block 
        // yoohoo
        // ...
       }

       {/* This is a block 
         yoohoo
         ...
         */
       }
    </p>
  )

}
...

Invalid:

...
render() {

  return (
    <p>
       {// This is not a comment! oops! }

       {//
        Invalid comment
       //}
    </p>
  )

}
...
Mehdi Raash
  • 8,721
  • 2
  • 29
  • 42
14

{/*
   <Header />
   <Content />
   <MapList />
   <HelloWorld />
*/}
harun ugur
  • 1,718
  • 18
  • 18
7
{
    // Any valid JavaScript expression
}

If you wonder why it works, it's because everything that's inside curly braces { } is a JavaScript expression.

So this is fine as well:

{ /*
         Yet another JavaScript expression
*/ }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bar Horing
  • 5,337
  • 3
  • 30
  • 26
  • {//} this isn't working, I have checked, can you please specify, I am trying to comment it inside the render function, this only works if there is new line after the curly brace and same case for the closing curly brace (it should be on the new line), – Irshad Babar Mar 09 '19 at 14:13
  • @Irshad Babar: *"this isn't working"*: What happens (or doesn't happen)? What are the symptoms? – Peter Mortensen Nov 04 '21 at 20:13
7

JSX Comments Syntax: You can use

{/** 
  your comment 
  in multiple lines
  for documentation 
**/} 

or

{/* 
  your comment 
  in multiple lines
*/} 

for multiple lines comment. And also,

{ 
  //your comment 
} 

for single line comment.

Note: The syntax:

{ //your comment } 

doesn't work. You need to type braces in new lines.

Curly braces are used to distinguish between JSX and JavaScript in a React component. Inside curly braces, we use JavaScript comment syntax.

Reference: click here

7

According to React's Documentation, you can write comments in JSX like so:

One-line Comment:

<div>
  {/* Comment goes here */}
  Hello, {name}!
</div>

Multi-line Comments:

<div>
  {/* It also works 
  for multi-line comments. */}
  Hello, {name}! 
</div>
Manuel Abascal
  • 5,616
  • 5
  • 35
  • 68
5

JavaScript comments in JSX get parsed as text and show up in your application.

You can’t just use HTML comments inside of JSX because it treats them as DOM nodes:

render() {
  return (
    <div>
      <!-- This doesn't work! -->
    </div>
  )
}

JSX comments for single line and multiline comments follows the convention

Single line comment:

{/* A JSX comment */}

Multiline comments:

{/*
  Multi
  line
  comment
*/}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Venkatesh Manohar
  • 2,125
  • 1
  • 18
  • 19
4

Conditional rendering

This approach mentioned on the React docs will also work with nested /**/ comments, unlike the {/**/} approach, e.g.:

{false && <>
<div>
  Commented out.
  /* Anything goes. */
</div>
</>}

Full example:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello, World!</title>
<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.14.7/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
ReactDOM.render(
  <div>
    before
    {false && <>
    <div>
      Commented out.
      /* Anything goes. */
    </div>
    <div>
      Also commented out.
      /* Anything goes. */
    </div>
    </>}
    after
  </div>
  ,
  document.getElementById('root')
);
</script>
</body>
</html>

renders just beforeafter.

Ah, just noticed, one downside of this is that linters like typescript could complain about stuff in the "comment" that is not correct.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
2

Here are 6 ways of commenting in React:

  1. Multi-line TypeScript comment
  2. HTML Attribute comment
  3. Single line JSX comment
  4. Single-line JSX comment
  5. Multi-line JSX comment
  6. Single-line JavaScript comment
/**
 * 1. Multi-line
 * TypeScript comment
 * @constructor
 */

export const GoodQuote = observer(({model} : { model: HomeModel }) => {

    console.log(model.selectedIndex)
    return useObserver(() =>
        <div /* 2. HTML attribute comment */ onClick={() => model.toggleQuote()}>
            <p>{model.quotes[model.selectedIndex]}</p>
            {
                // 3. Single-line comment
            }
            { /* 4. True Single-line comment */}
            { /*
              5. Multi-line
              React comment
            */ }
        </div> // 6. Javascript style comment

    )
})
Code on the Rocks
  • 11,488
  • 3
  • 53
  • 61
1

To write comments in JSX markup, you have to put them inside of curly braces { }

This is because without telling React that the comments is JavaScript code, it will read every slash / as part of an HTML node.

You can find more details about comments in JSX at https://thelonecoder.dev/javascript/react-js/how-to-write-comments-in-react/

Here's how to properly add the comment you tried to write in your render method:

  render() {
    return (
      <div className="dropdown">
        {
          // whenClicked is a property not an event, per see.
        }
        <Button whenClicked={this.handleClick} className="btn-default" title={this.props.title} subTitleClassName="caret"></Button>
        <UnorderedList />
      </div>
    )
  }

Note that you have to add a single-line // comment on its own line, otherwise you will be commenting out the closing brace }

The same syntax works for multi-line /* */ comments:

{
  /* This is a multi-line
     comment! */
}
christian_js
  • 298
  • 3
  • 11