32

I have a function that takes some arguments and renders an SVG. I want to dynamically import that svg based on the name passed to the function. It looks like this:

import React from 'react';

export default async ({name, size = 16, color = '#000'}) => {
  const Icon = await import(/* webpackMode: "eager" */ `./icons/${name}.svg`);
  return <Icon width={size} height={size} fill={color} />;
};

According to the webpack documentation for dynamic imports and the magic comment "eager":

"Generates no extra chunk. All modules are included in the current chunk and no additional network requests are made. A Promise is still returned but is already resolved. In contrast to a static import, the module isn't executed until the call to import() is made."

This is what my Icon is resolved to:

> Module
default: "static/media/antenna.11b95602.svg"
__esModule: true
Symbol(Symbol.toStringTag): "Module"

Trying to render it the way my function is trying to gives me this error:

Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

I don't understand how to use this imported Module to render it as a component, or is it even possible this way?

6
  • Does your svg display correctly if you statically import?
    – wederer
    Apr 21, 2020 at 8:42
  • Yes! If I do a regular import MyIcon from './icons/myicon.svg' I can render it like <MyIcon />.
    – Majoren
    Apr 21, 2020 at 8:44
  • You might have to store the resolved SVG in a state instead.
    – junwen-k
    Apr 21, 2020 at 9:08
  • @dev_junwen Correct, but storing it in state still doesn't enable me to render it as an inline svg.
    – Majoren
    Apr 21, 2020 at 13:42
  • Or another rather "dynamic" way is maybe you can define a map of name to SVG components, then use the bracket notation syntax iconMap[name] to retrieve the correct SVG. I haven't tested it yet but I think that could work. You will need to import all SVG in that case and assign it to the map.
    – junwen-k
    Apr 22, 2020 at 3:49

7 Answers 7

58

You can make use of ref and ReactComponent named export when importing SVG file. Note that it has to be ref in order for it to work.

The following examples make use of React hooks which require version v16.8 and above.

Sample Dynamic SVG Import hook:

function useDynamicSVGImport(name, options = {}) {
  const ImportedIconRef = useRef();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState();

  const { onCompleted, onError } = options;
  useEffect(() => {
    setLoading(true);
    const importIcon = async () => {
      try {
        ImportedIconRef.current = (
          await import(`./${name}.svg`)
        ).ReactComponent;
        if (onCompleted) {
          onCompleted(name, ImportedIconRef.current);
        }
      } catch (err) {
        if (onError) {
          onError(err);
        }
        setError(err);
      } finally {
        setLoading(false);
      }
    };
    importIcon();
  }, [name, onCompleted, onError]);

  return { error, loading, SvgIcon: ImportedIconRef.current };
}

Edit react-dynamic-svg-import

Sample Dynamic SVG Import hook in typescript:

interface UseDynamicSVGImportOptions {
  onCompleted?: (
    name: string,
    SvgIcon: React.FC<React.SVGProps<SVGSVGElement>> | undefined
  ) => void;
  onError?: (err: Error) => void;
}

function useDynamicSVGImport(
  name: string,
  options: UseDynamicSVGImportOptions = {}
) {
  const ImportedIconRef = useRef<React.FC<React.SVGProps<SVGSVGElement>>>();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error>();

  const { onCompleted, onError } = options;
  useEffect(() => {
    setLoading(true);
    const importIcon = async (): Promise<void> => {
      try {
        ImportedIconRef.current = (
          await import(`./${name}.svg`)
        ).ReactComponent;
        onCompleted?.(name, ImportedIconRef.current);
      } catch (err) {
        onError?.(err);
        setError(err);
      } finally {
        setLoading(false);
      }
    };
    importIcon();
  }, [name, onCompleted, onError]);

  return { error, loading, SvgIcon: ImportedIconRef.current };
}

Edit react-dynamic-svg-import-ts


For those who are getting undefined for ReactComponent when the SVG is dynamically imported, it is due to a bug where the Webpack plugin that adds the ReactComponent to each SVG that is imported somehow does not trigger on dynamic imports.

Based on this solution, we can temporary resolve it by enforcing the same loader on your dynamic SVG import.

The only difference is that the ReactComponent is now the default output.

ImportedIconRef.current = (await import(`!!@svgr/webpack?-svgo,+titleProp,+ref!./${name}.svg`)).default;

Also note that there’s limitation when using dynamic imports with variable parts. This SO answer explained the issue in detail.

To workaround with this, you can make the dynamic import path to be more explicit.

E.g, Instead of

// App.js
<Icon path="../../icons/icon.svg" />

// Icon.jsx
...
import(path);
...

You can change it to

// App.js
<Icon name="icon" />

// Icon.jsx
...
import(`../../icons/${name}.svg`);
...
45
  • 5
    Btw @dev_junwen ReactComponent never worked for me, I have no idea how this code works in your CodeSandbox, but .ReactComponent just returns undefined for me. I hade to change it and use .default as in @Enchew's example below. I found some great documentation on this here if you go down to "Importing defaults": developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    – Majoren
    May 14, 2020 at 10:41
  • 2
    @Willege I've updated the answer. Feel free to take a look at the code sample.
    – junwen-k
    Jul 6, 2020 at 17:04
  • 2
    @dev_junwen Unfortunately this solution doesn't work me. I've tried everything. Even if I download the code from CodeSandbox and install all dependencies from scratch with npm install, the SVG images are not loaded. I also don't get an error message. Is there something I'm doing wrong (maybe webpack, babel or typescript configuration)?
    – miu
    Jul 9, 2020 at 8:49
  • 2
    @mamiu Are you using Create React App ? If not you will need to setup inline svg loader manually. This answer might help.
    – junwen-k
    Jul 9, 2020 at 8:56
  • 3
    For anyone still getting undefined, there is a bug for dynamic webpack loading when the "issuer" property is set for svgs (github.com/webpack/webpack/discussions/…). The fix is removing the "issurer" config from the svg loader in the webpack config. Since we are using create-react-app, and haven't ejected, we utilized patch-package to remove those lines from the webpack config, and now everything is working. Feb 13, 2022 at 6:09
15

Your rendering functions (for class components) and function components should not be async (because they must return DOMNode or null - in your case, they return a Promise). Instead, you could render them in the regular way, after that import the icon and use it in the next render. Try the following:

const Test = () => {
  let [icon, setIcon] = useState('');

  useEffect(async () => {
    let importedIcon = await import('your_path');
    setIcon(importedIcon.default);
  }, []);

  return <img alt='' src={ icon }/>;
};
6
  • 4
    This probably works for an img tag where the source will be importedIcon.default, as you wrote, but it doesn't work in my case with an inline svg, where I want to render it as <Icon />. I tried your approach with an async useEffect, but then I need to setIcon with the whole Module, not importedIcon.default (the file path), then rendering it like <Icon />, and it gives me the error Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
    – Majoren
    Apr 21, 2020 at 12:30
  • Why do you need to render it as an <Icon> ? What does this approach give you and is there any difference, that can't be overcome by using <img>
    – Enchew
    Apr 21, 2020 at 12:48
  • 2
    How would I then change the properties of the svg if it's a img tag, like the fill color of the icon? Is it possible with an img tag?
    – Majoren
    Apr 21, 2020 at 13:38
  • Effects can't host an async function. They return a promise which gets invoked as a cleanup function. robinwieruch.de/react-hooks-fetch-data Aug 31, 2020 at 10:14
  • Regardless of what the original question is, this probably is the best answer for "dynamically import local files". This works well when I have a list of file URLs and load dynamically.
    – Hoon
    Jan 5, 2021 at 22:45
5

I made a change based on answer https://github.com/facebook/create-react-app/issues/5276#issuecomment-665628393

export const Icon: FC<IconProps> = ({ name, ...rest }): JSX.Element | null => {
      const ImportedIconRef = useRef<FC<SVGProps<SVGSVGElement>> | any>();
      const [loading, setLoading] = React.useState(false);
      useEffect((): void => {
        setLoading(true);
        const importIcon = async (): Promise<void> => {
          try {
            // Changing this line works fine to me
            ImportedIconRef.current = (await import(`!!@svgr/webpack?-svgo,+titleProp,+ref!./${name}.svg`)).default;
          } catch (err) {
            throw err;
          } finally {
            setLoading(false);
          }
        };
        importIcon();
      }, [name]);

      if (!loading && ImportedIconRef.current) {
        const { current: ImportedIcon } = ImportedIconRef;
        return <ImportedIcon {...rest} />;
      }
      return null;
    };
1
  • Thanks @kraken711 for your insight. When I try your approach I am getting an error: Module not found: Can't resolve @svgr/webpack?-svgo,+titleProp,+ref!. I tried : 1. await import(!!@svgr/webpack?-svgo,+titleProp,+ref!./[path_to_icon_folder]/${name}.svg)) 2. await import(!!@svgr/webpack?-svgo,+titleProp,+ref!./${name}.svg))
    – b-asaf
    Mar 24, 2022 at 9:44
2

One solution to load the svg dynamically could be to load it inside an img using require, example:

<img src={require(`../assets/${logoNameVariable}`)?.default} />
1

i changed my code to this and work:

import { ReactComponent as Dog } from './Dog.svg';

use like this:

<Dog />

or if it is dynamic:

 import * as icons from '../../assets/categoryIcons';

 const IconComponent = icons[componentName??'Dog'];

 <IconComponent fill='red' />
0

Another solution, even if I like the initial one 🙏🏻

Available for React version 16.6.0 and greater, I used the lazy function and Suspense to dynamically load my sprites.

const IconSprites = React.lazy(async () => {
   return { default: (await import(`sprites/.svg`)).ReactComponent }
})

And

export default function App(): JSX.Element {
  ...
  return (
   <Suspense>
    <IconSprites style={{ display: 'none' }} />
   </Suspense>
   ...
  )
}
-1

I dynamically fetched the SVG file as text and then put the SVG within a div dangerouslySetInnerHTML.

  const Icon = ({ className, name, size = 16 }: IconProps) => {
  const [Icon, setIcon] = React.useState("");

  React.useEffect(() => {
    fetch(`/icons/${name}.svg`)
      .then((res) => res.text())
      .then((res) => {
        if (res.startsWith("<svg")) return setIcon(res);
        console.error(
          `Icon: "${name}.svg" not found in ${process.env.PUBLIC_URL}/icons`
        );
        return setIcon("");
      });
  }, [name]);

  if (!Icon) return null;

  return (
    <div
      className={classNames("icon", className)}
      style={{ width: !size ? "100%" : size + "px", height: "100%" }}
      dangerouslySetInnerHTML={{ __html: Icon }}
    />
  );
};

Preview on Codesandbox

You can automatically change the color of your svg by giving it a fill value of "currentColor".

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.