How to Write Comments in React and JSX

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:
const 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:
const 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:
const 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:
const App = () => {
return (
<div>
{/* This is a comment. */}
<h1>Hello World</h1>
</div>
);
}
This is also how you leave multi-line comments in JSX:
const 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!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!