13

I found a much upvoted answer to a question with the following code:

var condition = true;

return (
  <Button {...condition ? {bsStyle: 'success'} : {}} />
);

Why is the ... required? If I omit it, babel complains to me that:

repl: Unexpected token, expected ...

It looks like the spread syntax, but condition is a boolean. I'm having trouble finding docs that explain what is going on.

2
  • 1
    It is JSX spread. The ... has lower precedence, so the conditional operator expression is evaluated first and then the returned object (either the one with bsStyle property or the empty one) is spread.
    – zerkms
    Commented Jan 8, 2017 at 4:06
  • 1
    gist.github.com/sebmarkbage/07bbe37bc42b6d4aef81
    – zerkms
    Commented Jan 8, 2017 at 4:07

2 Answers 2

8

If you check out MDN: Spread operator:

The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.

If you see, the spread operator inside the jsx syntax to evaluate expression, then

<Button {...condition ? {bsStyle: 'success'} : {}} />

Would become something like, (after babel run with react bootstrap example):

_react2.default.createElement(_reactBootstrap.Button, condition ? { bsStyle: 'success' } : {})

It can also be written as:

<Button bsStyle={condition ? 'success' : ''}  />

Which, then means you are passing the props bsStyle with empty string.

So in order to conditionally pass the props itself, you can leverage the spread operator and evaluate the expression. This helps us to pass multiple props on with conditions:

<Button {...condition ? {bsStyle: 'success', bsSize:"large"} : {}} />

Rather than:

<Button bsStyle={condition ? 'success' : ''} bsSize={condition ? 'large' : ''} />
2

You are using a boolean to return an object. The spread operator ... usage is for spreading that object, so you can make it more readable for yourself by using parenthesis:

var condition = true;
<Button { ...(condition ? {bsStyle: 'success'} : {}) } />

Which is equivalent to this, if your variable is true:

<Button { ...{bsStyle: 'success'} } />

or this one if your variable is false:

<Button { ...{} } />

Not the answer you're looking for? Browse other questions tagged or ask your own question.