0
votes

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

2

2 Answers

1
votes

As we know this.props is also an object just like obj1 why does JSX spreads differently?

The {} syntax in JSX is used for JavaScript expressions, so when we use {} it isn't considered as an object literal.

That's the reason we use something like someProp={{bla: 'foo'}} when we want to pass an object because the outer pair is to tell that we will have an expression inside it.

In short, using {} in JSX doesn't create an object.

You can read more about spread attributes.

0
votes

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 values a and b respectively.

const App = (props)=>{
   const {a,b} = props; // Object De-structuring
}

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.

const App= ({a,b})=>{ // Here we are De-Structuring from our props object
   console.log(a);
   console.log(b);
}

App({...obj1}); // This is same as App(a,b)

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 do

let obj1 = {a:1,b:2}

let obj2 = {...obj1} 

obj2 is clone of obj1. A complete new object. obj1 and obj2 are now two different objects in memory not just the references.