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.
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' : ''} />
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 { ...{} } />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With