0

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?

1 Answers1

0

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>
    );
  })}
yohanes
  • 2,365
  • 1
  • 15
  • 24
  • Hello, thank you for it. It works well! Im just still thinking. How it can be done create component via by cName? Maybe i will expand and it could be useful to know how. :) –  Jul 13 '22 at 08:34
  • you can put the Component into an object and call it by the key which is cName in this case. you can read here https://stackoverflow.com/questions/30172433/create-an-instance-of-a-react-class-from-a-string and here https://www.storyblok.com/tp/react-dynamic-component-from-json – yohanes Jul 13 '22 at 09:00