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
  • Do you have these components already created? Commented Jul 12, 2022 at 21:55

1 Answer 1

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

2 Comments

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. :)
you can put the Component into an object and call it by the key which is cName in this case. you can read here stackoverflow.com/questions/30172433/… and here storyblok.com/tp/react-dynamic-component-from-json

Your Answer

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