Mekatoo
Mekatoo

Reputation: 69

Passing react props as object

I find this syntax so weird.

     <>
      {items.map((item, i) => {
        return <ItemComponent key={i} {...{ [resourceName]: item }} />;
      })}
    </>

Can you explain it please? I know that in Parent component now I get name prop, but IDK how did this happen..

Upvotes: 0

Views: 855

Answers (1)

Apolo
Apolo

Reputation: 4050

I don't have the full context so here's my guess:

resourceName is a variable describing which prop will be set on ItemComponent.

you can't write resourceName={item} because then ItemComponent would have a property "resourceName" instead of whatever value is stored inside resourceName.

So the workaround for this is to create an object with only one key being the value of resourceName associated to the item object:

const itemComponentProps = {
  [resourceName]: item;
};

If you are not familiar with this syntax, it's to use dynamic keys on objects.

example:

const dynamicKey = 'foo';
const obj = {
  [dynamicKey]: 'bar'
}
console.log(obj[dynamicKey]); // bar
console.log(obj.foo); // bar

and you spread this object to the component:

<ItemComponent key={i} {...itemComponentProps} />

Upvotes: 1

Related Questions