Why can't I write a JSX comment inside an element tag?

I follow the general scheme of splitting tags with multiple attributes into multiple lines, for example.

<div className="foo" style={{ fontWeight: "bold" }} /> 

I would like to add a comment inside this declaration, for example.

 <div className="foo" {/* This is only temporary */} style={{ fontWeight: "bold" }} /> 

However, the above syntax does not work; I get:

 SyntaxError: Unexpected token, expected ... (45:96) 

(indicating closing } in temporary */} ). Is it possible to add a comment inside a tag in JSX, and if so, what syntax should I use?

+5
source share
2 answers

The short answer is “you can't,” but there are different ways to fake it. The simplest, I think, should come up with a different meaning:

 <img alt={"settings link" /* This is just temporary */} src="http://www.example.com/foo.jpg" /> 

This is slightly less than optimally understood, but all we have done is move the bracket up one line. This converts the "settings" link from the JSX HTML-esque value to a Javascript expression that just has a comment.

It has the advantage of associating a comment with a separate attribute, rather than with the tag as a whole. I think this is clearer; If you really want to comment on a tag, you'd better move it to the top.

If your goal was to comment on some attribute, yes, that is a bit unclear. But it should be clear enough not to comment when you get around it.

+3
source

I think you confuse props and children. When you do:

 <div className="foo" {/* bar */} > 

You are trying to use the built-in JSX expression, as if you were passing the details inside an open tag, this is NOT allowed. When you have an element, the opening tag can only contain deconstructed objects or prop=value values, so the reason why it expects ... is to deconstruct the object with details and values, for example:

 const props = { className: "foo" } <div {...props}> 

You cannot comment inside a tag because the tag does not allow JSX inline expressions. JSX expressions are only allowed as children:

 {/* bar */} <div className="foo" > 

In this example, the expression is not inside the open tag of the element and is allowed.

+2
source

All Articles