reactjscommerce.js

React.js - Accessing the elements of an object passed as prop through map function


So I am building an e-commerce app on react using commerce.js

I am passing the cart object(image attached) as props and mapping it using the cart function as below


const CartContainer = ({cart}) => {

    
    return(
    
        <div className = "container mx-auto"> 
             <div className="grid grid-rows-3 gap-2 auto-cols-max" >
             {/*Calling the cart item component to render the Cart item one by one*/}
            
              {
                 Object.values(cart).map((item,index) =>
                 (<CartItem item={item} key={index}/>))
             } 

             

            </div>
        </div>
        
        )

}

And i am trying to list the elements of the cart as below but it is not working

const Cart = ({item}) =>
{
    
    

    return (
      <div className="rounded overflow-hidden shadow-lg">
      <div className="px-1 py-1">
       <div className="text-s">{item.line_items.name}</div>
    </div>
    </div>

I am calling the cart component this way

   <CartContainer cart = {cart}/>

How do i access the elements of line_items

enter image description here


Solution

  • Object.values() will do exactly as the name implies it will take the values of an object and turn them into an array. You are not passing the item in your Component but you render a Cart for each value.