I came cross this code, and I don't understand {...{ [resourceName]: item }} inside the props inside the RegularList.js file.
I have two questions:
sth.=sth.{...{ [resourceName]: item }} trying to copy here?Here's my code:
RegularList.js
export const RegularList = ({
items,
resourceName,
itemComponent: ItemComponent,
}) => {
return (
<>
{items.map((item, i) => (
<ItemComponent key={i} {...{ [resourceName]: item }} />
))}
</>
);
};
App.js
const products = [{
name: 'Flat-Screen TV',
price: '$300',
description: 'Huge LCD screen, a great deal',
rating: 4.5,
}, {
name: 'Basketball',
price: '$10',
description: 'Just like the pros use',
rating: 3.8,
}, {
name: 'Running Shoes',
price: '$120',
description: 'State-of-the-art technology for optimum running',
rating: 4.2,
}];
<RegularList
items={products}
resourceName="product"
itemComponent={SmallProductListItem} />
SmallProductListItem.js
export const SmallProductListItem = ({ product }) => {
const { name, price } = product;
return (
<h3>{name} - {price}</h3>
);
}
{ [resourceName]: item }
Is creating a new Object with a dynamic key resourceName
...{}
Is spread operator.
So what is achieve here, is you pass a dynamic prop resourceName to your component.
For example, if resourceName === "foo" your ItemComponent will have the prop foo:
<ItemComponent foo={item} />