Synchro
Synchro

Reputation: 1269

React - How to pass an object inside a map array

I am creating a sidebar in my React application, before I used an array with objects for routing

SideBarItem.js

const SidebarItems = [
    {
        names: "General",
    },
    {
        name: "E-commerce",
        route: '/Maps',
    },
    {
        name: "Maps",
        route: '/Maps',
    },
    {
        names: "About",
    },
    {
        name: "Calendar",
        route: '/Calendar'
    },
];

export default SidebarItems;

Lesson.js

<ul>
    {SidebarItems.map((item, index) => {
        return (
            <>
                {item.names && (
                    <li className="header-menu">
                        <span>{item.names}</span>
                    </li>
                )}

                {item.name && (
                    <li>
                        <i className="fa fa-folder"></i>
                        <Link to={`${path}` + item.route}
                              className="link">{item.name}</Link>
                    </li>
                )}
            </>
        );
    })}
</ul>

And I got this side bar with links and paragraphs

enter image description here

The names property from the SidebarItems object is a simple <span> tag.

But now I use a different approach instead of creating an object with properties i use map it makes my work easier

const SidebarItems = ['Calendar', 'Messages', 'Notifications'].map((itemName) => ({
    name: itemName,
    route: `/${itemName}`
}));

This code performs the same logic as the old code. But I can't add the names property, I don't know how to do it, I tried to create an object inside an array

const SidebarItems = ['Calendar', 'Messages', {names: "General"}, 'Notifications'].map((itemName) => ({
    name: itemName,
    names: itemName.names,
    route: `/${itemName}`
}));

But I get an error - Error: Objects are not valid as a React child (found: object with keys {names}). If you meant to render a collection of children, use an array instead.

How can I solve this problem?

Upvotes: 1

Views: 787

Answers (1)

Taghi Khavari
Taghi Khavari

Reputation: 6582

Based on the array you're looping through, Here is what you need to do

const SidebarItems = [
  "Calendar",
  "Messages",
  { names: "General" },
  "Notifications",
].map((itemName) => {
  if (typeof itemName === "string") {
    return {
      name: itemName,
      names: itemName.names || "",
      route: `/${itemName}`,
    };
  } else {
    return {
      name: itemName.names,
      names: itemName.names,
      route: `/${itemName.names}`,
    };
  }
});

Upvotes: 1

Related Questions