Skip to content
react

How to Add Comments in React JSX

Mar 15th, 2021Abhishek EH6 Min Read

Comments inside a React component

If you wish to add comments inside a react component then it is similar to that of Javascript. That is:

  • Line comments can be added after //
Line Comment Example
1import React from "react"
2
3const App = () => {
4 // This is a line comment
5 return <div>App</div>
6}
7
8export default App
  • Block comments can be added after /* and before */
Block Comment Example
1import React from "react"
2
3const App = () => {
4 /* This is a block comment
5 * This can stretch to multiple lines
6 * Hence, also called multi-line comment
7 */
8 return <div>App</div>
9}
10
11export default App

Comments inside JSX

Adding comments inside JSX is a bit different. You might think that JSX looks like HTML and I can use the <!-- --> tag for commenting, however that will not work in JSX.

If you want to add comments inside the JSX block then you will have to include them inside the flower braces {}

1import React from "react"
2
3const App = () => {
4 return (
5 <div>
6 {/* This is a line comment inside JSX */}
7 <p>This a paragraph</p>
8 <p>This a paragraph</p>
9 <p>This a paragraph</p>
10 <p>This a paragraph</p>
11 </div>
12 )
13}
14
15export default App

Block comments do not have any special syntax. It is the same as above with comments spread to multiple lines:

1import React from "react"
2
3const App = () => {
4 return (
5 <div>
6 {/* This is a
7 multi line comment
8 inside JSX */}
9 <p>This a paragraph</p>
10 <p>This a paragraph</p>
11 <p>This a paragraph</p>
12 <p>This a paragraph</p>
13 </div>
14 )
15}
16
17export default App

If you want to use // for commenting, then you can use that too:

1import React from "react"
2
3const App = () => {
4 return (
5 <div>
6 {
7 //This is a line comment inside JSX (or is it?)
8 }
9 <p>This a paragraph</p>
10 <p>This a paragraph</p>
11 <p>This a paragraph</p>
12 <p>This a paragraph</p>
13 </div>
14 )
15}
16
17export default App

You could also comment HTML blocks, if you don't want them in your component as shown below:

1import React from "react"
2
3const App = () => {
4 return (
5 <div>
6 <p>This a paragraph</p>
7 <p>This a paragraph</p>
8 {/*
9 <p>This a paragraph</p>
10 <p>This a paragraph</p>
11 */}
12 </div>
13 )
14}
15
16export default App

Shortcut to add comments

While you could manually type {/* and */} every time you need to add a comment, but it becomes tedious to remember and type it. Let's learn the shortcut to add comments.

VS Code Editor

If you are using Windows/Linux you can use the following shortcut to add the comments:

Ctrl + /

If you are using Mac:

Cmd + /

ATOM code Editor

If you are using Windows/Linux you can use the following shortcut to add the comments:

Ctrl + Alt + /

If you are using Mac:

Cmd + Alt + /

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2021 CodingDeft.Com