How can I use comments inside the render
method in a React component?
I have the following component:
\'use strict\';
1) // (Double Forward Slash) is used to comment only single line in react native code but it can only be used outside of the render block. If you want to comment in render block where we use JSX you need to use the 2nd method.
2) If you want to comment something in JSX you need to use JavaScript comments inside of Curly braces like {/comment here/}. It is a regular /* Block Comments */, but need to be wrapped in curly braces.
shortcut keys for /* Block Comments */:
Ctrl + / on Windows + Linux.
Cmd + / on macOS.
JSX Comments Syntax: You can use
{/**
your comment
in multiple lines
for documentation
**/}
or
{/*
your comment
in multiple lines
*/}
for multiple lines comment. And also,
{
//your comment
}
for single line comment.
Note: The syntax:
{ //your comment }
doesn't work. You need to type braces in new lines.
Curly braces are used to distinguish between JSX and JavaScript in a React component. Inside curly braces, we use JavaScript comment syntax.
Reference: click here
JavaScript comments in JSX get parsed as Text and show up in your app.
You can’t just use HTML comments inside of JSX because it treats them as DOM Nodes:
render() {
return (
<div>
<!-- This doesn't work! -->
</div>
)
}
JSX comments for single line and multiline comments follows the convention
Single line comment:
{/* A JSX comment */}
Multiline comments:
{/*
Multi
line
comment
*/}
On the other hand, the following is a valid comment, pulled directly from a working application:
render () {
return <DeleteResourceButton
//confirm
onDelete={this.onDelete.bind(this)}
message="This file will be deleted from the server."
/>
}
Apparantly, when inside the angle brackets of a JSX element, the //
syntax is valid, but the {/**/}
is invalid. The following breaks:
render () {
return <DeleteResourceButton
{/*confirm*/}
onDelete={this.onDelete.bind(this)}
message="This file will be deleted from the server."
/>
}
{
// any valid js expression
}
If you wonder why does it work? it's because everything that's inside curly braces { } is a javascript expression,
so this is fine as well:
{ /*
yet another js expression
*/ }
According to React's Documentation, you can write comments in JSX like so:
One-line Comment:
<div>
{/* Comment goes here */}
Hello, {name}!
</div>
Multi-line Comments:
<div>
{/* It also works
for multi-line comments. */}
Hello, {name}!
</div>