[reactjs] ReactJS - How to use comments?

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?

This question is related to reactjs react-native

The answer is


{ 
    // any valid js expression
}

If you wonder why does it work? it's because everything that's inside curly braces { } is a javascript expression,

so this is fine as well:

{ /*
         yet another js expression
*/ }

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.


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.


Two Ways to Add Comments in React Native

1) // (Double Forward Slash) is used to comment only single line in react native code but it can only be used outside of the render block. If you want to comment in render block where we use JSX you need to use the 2nd method.

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

shortcut keys for /* Block Comments */:

Ctrl + / on Windows + Linux.
Cmd + / on macOS.

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


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>
)

JavaScript comments in JSX get parsed as Text and show up in your app.

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
*/}  

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 link: https://reactjs.org/docs/faq-build.html#how-can-i-write-comments-in-jsx


_x000D_
_x000D_
{/*_x000D_
   <Header />_x000D_
   <Content />_x000D_
   <MapList />_x000D_
   <HelloWorld />_x000D_
*/}
_x000D_
_x000D_
_x000D_


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."
           />
}

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>

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>
  )

}
...

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to react-native

How to resolve the error on 'react-native start' React Native Error: ENOSPC: System limit for number of file watchers reached How to update core-js to core-js@3 dependency? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65 How can I force component to re-render with hooks in React? What is useState() in React? Getting all documents from one collection in Firestore ReactJS: Maximum update depth exceeded error React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH