1

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?

0

1 Answer 1

1

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}`,
    };
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.