When you begin to write your own React code, there’s something you’ll notice fairly quickly: normal JavaScript comments do not work in JSX. Writing comments in React and JSX markup works a little differently, but why? Let’s find out.
Writing Comments in React
First off, let’s get the elephant out of the room. To write comments in React, you have to surround them with curly braces ({ }
). So to add comments in some JSX markup, add curly braces and you can write your comment inside of them.
<div>
{ /* This is a comment */ }
</div>
You’ll notice that I’ve used the slash-star (/* */
) syntax instead of the double-slash (//
) syntax. That’s because a single-line comment spans an entire line, which would comment out the closing brace of the comment block!
Single-line comments should be on their own line:
{
// This is a comment!
}
And if you like, you can also use this format for multi-line slash-star comments
{
/* This is a long, multi-line comment.
You can describe what you're doing here
All programmers should write comments */
}
Why Don’t Regular JS Comments Work in React?
There’s a pretty good reason why bare JavaScript comments don’t work in JSX. It has to do with how React parses JSX code.
When React sees a slash in some JSX markup, it automatically tries to parse it as an HTML node. That’s because, as you know, slashes are used to close tags in HTML and JSX!
Therefore, we need to wrap our comments in curly braces. Curly braces let React know that we are going to embed some JavaScript code (not JSX code!) into the markup.
Yes, it’s clunky and annoying, but that’s the way it is. So get back to coding and write those comments!
One thought on “How to Write Comments in React/JSX”