Hi i am new to React and javascript development and would like to know the difference between
var a = { className: 'my-secondary-classname' };
<span className="my-span-classname" {...a}>abc</span>
and
var a = { className: 'my-secondary-classname' };
<span {...a} className="my-span-classname">abc</span>
Tried reading about spread props and still not clear about it
2
Answers
className is a prop. SO if you do
{...a}
and a is an object that contains className as a property, the value ofa.classname
will be applied to that component.If you do className before
{...a}
,a.className
will override the previously supplied classname.If you do className after
{...a}
, className will overridea.className
The spread operator here is no different to a spread on an object, as that’s what your doing.
So the spread will evaluate from left to right, so everything to the right will take precedence.
eg..
Notice how the first spread, we get ‘321’, and the second one it keeps the ‘123’.
To prove this is just the same as spreading an object, here is what the JSX for your first one looks like ->
So internally that JSX just gets converted into a
Object.assign()
-> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign