Spread Operator in JS environment
let obj1 = {a:1,b:2}
let obj2 = {...obj1}
console.log(obj2)
Above code outputs {a:1,b:2} Which is a copy of obj1
Spread Operator in JSX
let us assume this.props = {lib:'react',lang:'js'}
<App {...this.props}/>
would be same as
<App lib={this.props.lib} lang={this.props.lang}>
As we know this.props is also an object just like obj1 why does JSX spreads like lib='react,lang='js' instead of lib:'react',lang:'js'?
Is there a difference between JSX Spread Operator and Javascript Spread Operator?
I'm really Confused
In both cases it is a spread operator only and Javascript spread operator only. There is no such thing as JSX spread operator.
When we do
<App {...this.props}/>
, it is same as<App a="1" b="2"/>
in React. And in React these are added to the prop object of App class. From that prop object, we get access to the valuesa
andb
respectively.We are basically spreading the props which means passing these values as Props to the App component, . This is same as passing values to function using spread operator.
Think of it this way: Think of
App Component
as a function, which is taking spreaded object as arguments.Codepen code : https://codepen.io/emmeiWhite/pen/poEREEx?editors=1111
Try above code in Javascript file
Spread
...
operator can also be used to make a clone of the object when we doobj2
is clone of obj1. A complete new object. obj1 and obj2 are now two different objects in memory not just the references.