Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jsx require three dots in this code?

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.

like image 717
jay Avatar asked Jan 08 '17 03:01

jay


2 Answers

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' : ''} />
like image 78
Nagaraj Tantri Avatar answered Nov 03 '22 01:11

Nagaraj Tantri


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 { ...{} } />
like image 39
dashtinejad Avatar answered Nov 03 '22 00:11

dashtinejad