Table of Contents
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
//
1import React from "react"23const App = () => {4 // This is a line comment5 return <div>App</div>6}78export default App
- Block comments can be added after
/*
and before*/
1import React from "react"23const App = () => {4 /* This is a block comment5 * This can stretch to multiple lines6 * Hence, also called multi-line comment7 */8 return <div>App</div>9}1011export 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"23const 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}1415export 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"23const App = () => {4 return (5 <div>6 {/* This is a7 multi line comment8 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}1617export default App
If you want to use //
for commenting, then you can use that too:
1import React from "react"23const 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}1617export default App
You could also comment HTML blocks, if you don't want them in your component as shown below:
1import React from "react"23const 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}1516export 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!