d-dripz
d-dripz

Reputation: 85

Pass object into component as a prop and render each item in the object

GOAL: Pass object as a prop to a component and then render each item in the object in a p tag

Here is the code where I pass the object into my ProductDetails component as the bullets prop:

return (
    <div className="product">
          {products.map((product) => (
            <ProductDetails
              bullets={product.productBullets}
            />
          ))}
    </div>

This is what my productBullets object looks like:

productBullets: {secondBullet: " asdf", thirdBullet: "ads", firstBullet: " asdf", fourthBullet: "adf "}

I pass bullets as a prop from my ProductPage component to my ProductDetails component here:

function ProductDetails({ bullets }) {
  return (
    <div className="product__details">
        {bullets.map((bullet) => (
          <p>{bullet}</p>
        ))}
    </div>
  );
}

However, when I try to map through the object, the items don't render. Any help would be appreciated!

Upvotes: 0

Views: 50

Answers (1)

kind user
kind user

Reputation: 41893

The map function does not work because it's not an array, it's an object.

{Object.values(bullets || {}).map((bullet, i) => (
   <p key={i}>{bullet}</p>
))}

Upvotes: 2

Related Questions