jsx icon indicating copy to clipboard operation
jsx copied to clipboard

Curly braces for attribute expressions are pointless and ugly

Open ghost opened this issue 6 years ago • 4 comments

Originally submitted to facebook/react here: https://github.com/facebook/react/issues/11944 Relates to: https://github.com/facebook/jsx/issues/65

Do you want to request a feature or report a bug? Feature

What is the current behavior? Curly braces are required to delimit Javascript expressions in JSX attributes.

<MyComponent foo={bar(1, 2, 3)} />

What is the desired behavior? All Javascript expressions can be expressed without the need for {}.

<MyComponent foo=bar(1, 2, 3) baz="quirk" life=42 pi=3.1415 sum=(x + y) fancy=`Hello ${name}` onClick=()=>{ this.andThat() } />

In short, requiring {} around all of these is unnecessary although the last one is a bit ugly with the =()=> thing.

ghost avatar Jan 02 '18 14:01 ghost

One thing to consider here is that there is now a new thing to learn about when you have to use parenthesis instead.

Additionally, this doesn't play nicely with do-expressions if that's the route we're going but we might not.

sebmarkbage avatar Jan 03 '18 05:01 sebmarkbage

I see your point but I think in the wider context of learning JSX syntax it's not a huge leap. Another benefit of this approach is object literals, notably when using the style attribute/prop. The single rule to learn would be "parenthesis are required if the expression contains multiple symbols with the exception of function calls and function literals".

This may not be necessary either if parsed right-to-left with everything up to '=' being parsed as part of the expression and lone symbols that cannot be parsed as part of the expression being treated as value-less attributes. Personally I don't like that approach because it introduces ambiguity. E.g., <foo bar=1 + baz quirk /> would be parsed as <foo bar={1 + baz} quirk />... which is less clear than <foo bar=(1 + baz) quirk />.

I think I saw an issue related to do-expressions, not entirely sure what those are so I'll go and have a look but that sounds to me like some way of using do-while loops within attribute values. If that's the case then I don't see any reason to do that but I'm ignorant on this particular point.

ghost avatar Jan 03 '18 10:01 ghost

Do expressions allow you to use full statements inside of an expression and the last statement's result is used as the value of the expression. You can even use if in them instead of ternaries.

<foo Bar={do {
  const {data} = this.props;
  if ( data.foo ) {
    getFoo(); // return value used as Bar's value
  } else {
    getBar(); // return value used as Bar's value
  }
}} />

dantman avatar Mar 04 '18 09:03 dantman

It looks like it would work without the curlies too. They seem compatible to me.

Though I do wonder why not just use a function or assign a variable before the JSX expression?

ghost avatar Mar 05 '18 09:03 ghost