简体   繁体   中英

How can i create Component insted className generated from array? Using React.js

I'd like to ask you about how to create Component insted class. I've found this piece of code which works well

    {MenuItems.map((item, index) => {
      return (
        <WrapperLi
          key={index}>
          <Link
            className={item.cName}
            to={item.path}
            onClick={() => setClick(false)}
          >
            {item.title}
          </Link>

        </WrapperLi>
      );
    })}

Whole file MenuItems.js looks like this:

export const MenuItems = [
  {
    title: 'Marketing',
    path: '/marketing',
    cName: 'dropdown-link'
  },
  {
    title: 'Consulting',
    path: '/consulting',
    cName: 'dropdown-link'
  },
  {
    title: 'Design',
    path: '/design',
    cName: 'dropdown-link'
  },
  {
    title: 'Development',
    path: '/development',
    cName: 'dropdown-link'
  }
];

I hope i have simply question. Cuz i want have whole app in styled components i must create a component not className. Line className={item.cName} is responsible for creating className for every element of Array.

How to create Component named by cName value insted className please?

You don't need cName if your cName: 'dropdown-link' is equal for all link. So change your MenuItems into this:

const menuItems = [
  {
    title: "Marketing",
    path: "/marketing"
  },
  {
    title: "Consulting",
    path: "/consulting"
  },
  {
    title: "Design",
    path: "/design"
  },
  {
    title: "Development",
    path: "/development"
  }
];

and create your custom link let's say MenuLink (use your own style here)

const MenuLink = styled(Link)`
  padding: 20px;
  color: blue;
  text-decoration: none;
  &:hover {
    color: white;
    background: DodgerBlue;
  }
`;

and finally you can render them like so:

  {menuItems.map((item, index) => {
    return (
      <WrapperLi key={index}>
        <MenuLink to={item.path}>{item.title}</MenuLink>
      </WrapperLi>
    );
  })}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM