Need help with JSX Spread Attribute

I understand how to use JSX Spread Attribute, but I would like to understand how it works.

<TestComponent { ...{name: 'Tom', height: '1.8m'} } />

I assume the first pair of curl braces indicates whatever is enclosed are JS codes. Please correct me if I am wrong. If that is correct, then …{name: ‘Tom’, height: ‘1.8m’} is not valid JS syntax, as can be seen from this:

const props = ...{name: 'Tom', height: '1.8m' }  // Syntax error, unexpected token where the 3 periods are

const props = { ...{name: 'Tom', height: '1.8m' } } // This works.

Does that mean the first pair of curly braces is actually the syntax for JS object and is passed as the props object? If that is true, then this should work but it doesn’t.

<TestComponent { name: 'Tom', height: '1.8m' } />   // Syntax Error

So, how is { …{name: ‘Tom’} } passed on as props behind the scene?


This part becomes…

like this, behind the scene. So that , you can use those props inside defined component.

  • Outer bracket allow us to inject js expression inside component

  • Since object is an expression, its valid.

  • We use spread operator simply for adding items to arrays, combining arrays or objects.

with arrays,
const scores = [1 , 2, 3]
const newScores= [...scores, 4] // [ 1, 2, 3, 4]

with objects,
const user = {name : 'test', age: 27}
const newUser= {...user, major:'engineer'}
// {name: 'test', age: 27, major: 'engineer'}

By the way , in real-world applications, you will likely see this.