PositiveGuy
PositiveGuy

Reputation: 20162

Use spread props with additional props

How can I append another property? I have a react component where someone has passed in ...props and I want to append on an extra prop

 <AccountsStatus {...props} />

Upvotes: 10

Views: 11908

Answers (4)

raina77ow
raina77ow

Reputation: 106365

More concise approach to do this is based on using an object spread operator:

<AccountsStatus {...{...props, extraProp: extraValue}} />

To be able to use it, you'll need to configure Babel to use transform-object-rest-spread plugin.

Upvotes: 3

Nesha Zoric
Nesha Zoric

Reputation: 6620

Just send the prop above the spread operator:

<AccountsStatus
    otherProp={otherPropValue}
    {...props}
/>

Keep in mind to always specify it above the spread props. If you're passing the prop with same name in props, you probably want to override it. You can read more on props in this article, it's covering a lot of ways on how certain types of props are passed.

Upvotes: 0

cheersjosh
cheersjosh

Reputation: 1209

Bear in mind that the order in which you pass your props will determine which value is passed through to that component. This applies if there are two keys with the same name.

For example:

<AccountsStatus extraProp={extraValue} {...props} />

and

<AccountsStatus {...props} extraProp={extraValue} />

look the same, but in the first example, if you were spreading your props object which contained an extraProp key, it would overwrite the extraProp value you pass before it.

Upvotes: 28

Luan Nico
Luan Nico

Reputation: 5917

Just add in the sequence:

<AccountsStatus {...props} otherProp={true} />

Or you can clone props, add the other prop to the clone, and then do:

<AccountsStatus {...newProps} />

But I wouldn't recommend on doing that, you'd nee a lib to clone the object.

Upvotes: 12

Related Questions