MeltingDog
MeltingDog

Reputation: 15404

How do I use multiple spread props in a React component?

I am writing in TypeScript. I am passing two objects as props to my React. From searching around I see I do that as such:

<MyComponent {...obj1} {...obj2} />

But how do I then use them in my actual component file?

Variations of:

const MyComponent = ({ ...obj1, ...obj2 }) => {

Don't seem to work.

Would anyone know how this is done?

Upvotes: 3

Views: 256

Answers (1)

HosseinAgha
HosseinAgha

Reputation: 833

When you spread props in creating elements you lose the handle to them. Consider the following:

const foo = { a: 1, b: 2 };
const bar = { a: 3, d: 4 };
<MyComponent {...foo} {...bar}>

You'll get:

const MyCompnent = ({ a, b, d }) => // your code

So you'll have no reference to foo and bar, because you've spread both and the a prop may belong to either one depending on the spread order.
You can send foo and bar as individual props if you want access to them in component.

<MyComponent foo={foo} bar={bar}>

Upvotes: 3

Related Questions