To write comments in React JS we use the javascript comments and JSX object. It helps in adding useful information about the code and comment-out and ignore the extra code in the program.
Writing comments in React is done in these ways.
Table of Content
Steps to create React Application
Step 1: Create a React application with the following command:
npx create-react-app my-app
Step 2: Move to the project folder my-app with the following command:
cd my-app
Project Structure
Approach 1: Using JavaScript comments
These comments are made in the function and class definitions or where we are not writing any JSX code.
Syntax
// This is inline comment
/* This is a
multiline commnet */
Example: Comments for React Components. We can write comments in React using the double forward-slash // or the asterisk format /* */, similar to regular JavaScript.
import React, { Component } from 'react' ;
// This is a comment class App extends Component { /* This is
also a comment*/
render() {
return (
<div>
<h1>Welcome to GeeksforGeeks</h1>
</div>
);
}
} export default App;
|
Steps to tun the application: Use this command in the terminal window.
npm start
Output: This output will be visible on http://localhost:3000 on the browser.
Approach 2: Using JSX object
JSX object with the javascript comments can be used to commnet in the JSX code that is to be rendered on the UI.
Syntax:
{/* this is inline */}
{/* This is a
multiline comment*/}
Example: The above example does not work when we want to comment things inside the render block. This is because we use JSX inside the render block and must use multi-line comment in curly braces {/* */}.
import React, { Component } from 'react' ;
class App extends Component { render() {
return (
<div>
// This is not a valid comment
/* Neither is this */
{ /* THIS ONE IS A VALID COMMENT */ }
<h1>Welcome to GeeksforGeeks</h1>
</div>
);
}
} export default App;
|
Steps to run the application: Use this command in the terminal window.
npm start
Output: This output will be visible on http://localhost:3000 on the browser.
Note: We must remember, that even though JSX gets rendered just like normal HTML, it is actually a syntax extension to JavaScript. So, using <!– –> as we did with HTML and XML will not work.
import React, { Component } from 'react' ;
class App extends Component { render() {
return (
<div>
<!-- This is not a valid comment -->
{ /* THIS ONE IS A VALID COMMENT */ }
<h1>Welcome to GeeksforGeeks</h1>
</div>
);
}
} export default App;
|
Output: It will give the following error on the console window.