j obe
j obe

Reputation: 2039

Why does es6 spread behaviour change between objects and React components?

I'm trying to understand why es6 object spread behaviour is different between objects and when it's used in React components to spread props.

The following makes sense to me:

const a = {
  a:1,
  b:2
}

const c = {...a}

Now variable c will have the same properties as variable 'a' with key value pairs in this format of a:1, b:2.

This doesn't make sense:

<Mycomponent {...a} />

turns the props into "a={1} b={2}". Why does it behave in this way instead of the usual way which is key value pairs a:1, b:2?

I would like to understand why this works like this so I can better understand the language.

I've seen tutorials and articles which explain how spread works in both cases but I haven't found an answer why it spreads differently?

Upvotes: 1

Views: 111

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85102

<Mycomponent {...a} />

turns the props into "a={1} b={2}". Why does it behave in this way instead of the usual way which is key value pairs a:1, b:2?

But it is doing key/value pairs of a:1 and b:2. The following code...

<Mycomponent a={1} b={2} />

... tells react to create a props object that looks like { a: 1, b: 2 }. And when you use the spread syntax, it also tells react to create a props object that looks like { a: 1, b: 2}.

Upvotes: 1

Related Questions