Table of Contents
Comments can be a useful way to leave notes for yourself and other developers about anything in your code.
However, while it is straightforward in React, it can be a little tricky in JSX.
In this post, we'll learn how to write comments in React and JSX.
How to write comments in React
As mentioned before, leaving comments in React is straightforward.
This is because React components are just JavaScript functions.
Let's look at an example of a comment inside a React component:
JAVASCRIPTconst App = () => {
// This is a comment.
return (
<div>
<h1>Hello World</h1>
</div>
);
}
If you want to leave multi-line comments, you can use the following syntax:
JAVASCRIPTconst App = () => {
/*
This is a multi-line comment.
It can span multiple lines.
*/
return (
<div>
<h1>Hello World</h1>
</div>
);
}
How to write comments in JSX
Now, because JSX is not actually HTML, you can't use the same syntax for comments as you would in HTML.
For example, this will not work:
JSXconst App = () => {
return (
<div>
<!-- This is a comment. -->
<h1>Hello World</h1>
</div>
);
}
This is because JSX is actually just syntactic sugar for JavaScript.
To leave comments in JSX, you need to use the following syntax:
JSXconst App = () => {
return (
<div>
{/* This is a comment. */}
<h1>Hello World</h1>
</div>
);
}
This is also how you leave multi-line comments in JSX:
JSXconst App = () => {
return (
<div>
{/*
This is a multi-line comment.
It can span multiple lines.
*/}
<h1>Hello World</h1>
</div>
);
}
Conclusion
In this post, we learned how to write comments in React and JSX.
Simply use normal comments when inside a React component but switch to the curly braces syntax when inside JSX.
Thanks for reading!
Getting Started with TypeScript
How to Install Node on Windows, macOS and Linux
Create an RSS Reader in Node
How to Set Up Cron Jobs in Linux
How to deploy a Deno app using Docker
How to deploy a Node app using Docker
How to Scrape the Web using Node.js and Puppeteer
Getting Started with Handlebars.js
Learn how to build a Slack Bot using Node.js
Using Push.js to Display Web Browser Notifications
Getting Started with React
Getting Started with Vuex: Managing State in Vue
