tailwindlabs / heroicons

A set of free MIT-licensed high-quality SVG icons for UI development.
https://heroicons.com
MIT License
21.33k stars 1.28k forks source link

How to use in a map? #262

Closed JPortegijs closed 3 years ago

JPortegijs commented 3 years ago

I have a react Navigation component, where I loop over routes, each route has a icon property. How would I use the icon in the map?

This would be the array of the routes:

const routes = [{
    route: '/',
    title: 'Dashboard',
    exact: true,
    icon: 'Code',
  }]

And this is what the component returns:

return (
    <nav className="flex flex-col bg-gray-900 h-full w-56 text-white py-4 pr-2">
      {routes.map(({route, title, icon, exact}, index) => (
        <NavLink
          className="flex items-center text-gray-400 rounded-full rounded-l-none text-sm font-semibold py-3 px-6 hover:text-white"
          activeClassName="navigation-link-active"
          key={index}
          to={route}
          exact={typeof exact !== 'undefined' && exact}
        >
          <Icons.Code className="inline-block h-5 w mr-3" />
          {title}
        </NavLink>
      ))}
    </nav>
  );

Any help is appreciated!

Thanks in advance.

sonnes commented 3 years ago

@JPortegijs I ran into same issue. how did you solve this?

wsmd commented 3 years ago

You could import the entire module as an object and use the icon names to lookup its exports:

import * as icons from "@heroicons/react/solid";

const ComponentWithIcon: React.FC<{ iconName: keyof typeof icons }> = (props) => {
  const Icon = icons[props.iconName];
  return (
    <div>
      <Icon className="w-5 h-5" />
      <span>{props.iconName}</span>
    </div>
  );
};

Full example here: https://codesandbox.io/s/tailwindlabsheroicons262-lw2gr

Although, be carful here since you may loose tree-shaking by doing so. I recommend you explicitly re-export the icons you need from another file (import * as icons from '../path/to/icons'). This way you have control over the icons that ends up included in the bundle.