Why does jsx require three dots in this code?

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

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

Why is it required ...? If I omitted this, the granny complains to me that:

 repl: Unexpected token, expected ... 

It is similar to distribution syntax, but condition is logical. I am having trouble finding documents that explain what is happening.

+5
source share
2 answers

If you select MDN: Distribution Operator :

Distribution syntax allows you to expand an expression in places where several arguments (for function calls) or several elements (for massive literals) or several variables (for assignment of destructuring) are expected.

If you see the distribution operator inside the jsx syntax for evaluating an expression, then

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

It would be 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 means that you pass the bsStyle an empty string.

So, to conditionally transfer props, you can use the spread operator and evaluate the expression. This helps us to transfer several details with the conditions:

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

Instead

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

To return an object, use boolean . The distribution operator ... intended to distribute this object, so you can make it more understandable for yourself by using parentheses:

 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 { ...{} } /> 
0
source

Source: https://habr.com/ru/post/1262485/


All Articles