Reputation: 706
So I created the fiddle: https://jsfiddle.net/4ex7uh8g/
The problem is I don't understand the syntactic differences in the particular line of code of that fiddle.
Take a look at 24 line in JavaScript tab. Here it uses such syntax: <div style={{...spanStyle}}>
also I tried using such syntax as: <div style={spanStyle}>
and it also works fine, and when I inspected the style properties are injected identically, so for me it looks like everything is the same, just the difference in syntax, but I'm not really sure, could I be missing something or misunderstanding when choosing one over another?
I also did read this thread: What do these three dots in React do?
It explains some things about three dots operator, I'm quite familiar with this spread operator, but still in my provided examples I don't see what difference that spread operators does, it doesn't separate attributes and values it works the same as {spanStyle}, so for me {{...spanStyle}} and {spanStyle} act identical?
Would be really grateful if you could point out the difference if there's any and when and why should I use one syntax over another.
Upvotes: 5
Views: 2599
Reputation: 5695
When using a single pair of braces, you basically tell JSX you're going to embed a JS expression. When you have a second pair within the first, you're creating an inlined object literal (as you're already in JS context). When you specify styles through the style
property in JSX you have to supply an object, hence the double braces.
Using:
{{...spanStyle}}
just creates a new object literal and takes all the properties from spanStyle
using the spread operator (...
) thus, as you noticed already, you will get absolutely the same result as simply doing {spanstyle}
but with the overhead of creating an object clone.
Upvotes: 5
Reputation: 1125
First encasing brackets is for the JSX specification for javascript evaluated portions:
<div style={ Javascripty stuff in here }
So, first brackets starts up javascript mode essentially.
Next set of brackets is in javascript land, which in javascript {}
means new empty Object
Last piece of the puzzle is the spread operator ...
.
When you use the spread operator on an object within the declaration of another object, it sucks all the properties out of that object and applies it to the new object you are calling:
<div style={{...anotherObject}} />
So, if you remember the first brackets activates javascript stuff, it all starts making more sense.
Upvotes: 2
Reputation: 241
What you are looking for is the spread operator:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
With this syntax you can create a new object, and add some prop overriding any original object prop.
Example:
const spanStyle = {width: '100%', height: '400px'};
<div style={{...spanStyle, height: 'auto'}}>
If you dont need override anything, just skip spread!
Upvotes: 1