mozew's avatar

React: MUI Menu does not render although data exists (object vs array issue)

I am working on a React shopping cart component.

I pass a cart item as a prop to my CartItem component:

<CartItem item={item} qty={item.quantity} />

I confirmed with console.log that props.item exists and contains data:

{
  _id: "...",
  productTitle: "...",
  price: 15000000,
  ram: "6GB"
}

I want to show a Material-UI Menu that lists all available RAM options. However, nothing renders and I get errors like:

"Cannot read properties of undefined (reading 'map')"

This is my code:

{Array.isArray(props?.item) && props.item.length > 0 && (
  <Menu open={openRam} anchorEl={ramAnchorEl}>
    {props.item.map((item, index) => (
      <MenuItem key={index}>
        {item.name}
      </MenuItem>
    ))}
  </Menu>
)}

The problem seems to be that props.item is an object, not an array, so Array.isArray returns false and .map() never runs.

My question: What is the correct way to render a list (MUI Menu) when the data source is an object, but the selectable options (RAM list) should come from another field or related data?

Should I:

  • Convert the object to an array?
  • Or pass a separate ramOptions array to the component?
0 likes
2 replies
mbg22's avatar

Hi @mozew Please explain your data structure further. From your console log i don't see where the related data / the actual items should be that you're trying to map over and render.

JussiMannisto's avatar

props.item is a single object, so iterating over it makes no sense. If you had an array of multiple items, that would be a different story.

If you want to list several options, you of course have to pass those options to the component.

Please or to participate in this conversation.