简体   繁体   中英

import dynamically react icons

I need to import a icon dynamically with the props will receive in the component and return the icon compatible with this, i have a question about this:

import { useEffect, useState } from 'react';

export default function Icon({ libraryName, iconName }) {
  const [icon, setIcon] = useState(null);

  async function getIcon() {
    const path = `../../../node_modules/react-icons/${libraryName}`;
    const returnedIcon = await import(path);
    if (returnedIcon) setIcon(returnedIcon[iconName]);
  }

  useEffect(() => {
    if (iconName) {
      getIcon();
    } else {
      setIcon(null);
    }
  }, []);

  return <span>{icon}</span>;
}


So, if you call this component for example with this

<Icon libraryName="md" iconName="mdMonitor" />

This work!

But, maybe the const path can be change with another path?

I think that exist better way to do this, if any can help me i would be grateful.

You shouldn't be referencing node_modules from within your components. Your eventual production build will not have access to that directory, because the bundler (like webpack) will package up all of your various code and library files into a single JS file.

If you're using an icon library, you should import the icons just as you would any other JS module, and use them as you need.

If you need icons from multiple icon libraries, you'll need to npm install both libraries, and then in your UI code just import the ones you need from each library.

Maybe you need a wrapper for your icon:

import React from 'react';

export default function IconWrapper({icon}) {

  return <span>{icon}</span>;
}


and your UI code could look like this:

import React from 'react';
import {PlusIcon} from 'icon-lib-A';
import {MinusIcon} from 'icon-lib-B';

export default function App() {
  return (
    <div>
      <Icon icon={<PlusIcon} />
      <Icon icon={<MinusIcon} />
    </div>
  )
}

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