Burton
Burton

Reputation: 447

Using map on array of objects results in a errormessage

I am trying to figure out why this simple code does not work, it feels like I have done exactly the same thing many times before without errors. What have I done wrong?

import React, {useState} from 'react'
import { MenuItem } from '../menu-item/menu-item.component'
import './directory.styles.scss'

export const Directory = () => {
    const sections = [
        {
          title: 'hats',
          imageUrl: 'https://i.ibb.co/cvpntL1/hats.png',
          id: 1,
          linkUrl: 'shop/hats'
        },
        {
          title: 'jackets',
          imageUrl: 'https://i.ibb.co/px2tCc3/jackets.png',
          id: 2,
          linkUrl: 'shop/jackets'
        },
        {
          title: 'sneakers',
          imageUrl: 'https://i.ibb.co/0jqHpnp/sneakers.png',
          id: 3,
          linkUrl: 'shop/sneakers'
        },
        {
          title: 'womens',
          imageUrl: 'https://i.ibb.co/GCCdy8t/womens.png',
          size: 'large',
          id: 4,
          linkUrl: 'shop/womens'
        },
        {
          title: 'mens',
          imageUrl: 'https://i.ibb.co/R70vBrQ/men.png',
          size: 'large',
          id: 5,
          linkUrl: 'shop/mens'
        }
      ];

    return (
        <div className="directory-menu">
            {sections.map((title, imageUrl, id) => <MenuItem key={id} title={title} imageUrl={imageUrl}/>)}
        </div>
    )
}

Error Message:

Error: Objects are not valid as a React child (found: object with keys {title, imageUrl, id, linkUrl}). If you meant to render a collection of children, use an array instead.

Upvotes: 0

Views: 75

Answers (2)

Giorgi Moniava
Giorgi Moniava

Reputation: 28674

You are not destructuring properly i.e.

.((title, imageUrl, id) =>

should be

.(({title, imageUrl, id}) =>

Upvotes: 2

Nick Kinlen
Nick Kinlen

Reputation: 1404

Check out this post, it's a common React error.

You could also try something like this

Object.entries(sections).map((x)=>
    return x.title;
})

Upvotes: 0

Related Questions