Lazy loading SVG with CRA

Viewed 591

I want to lazy load SVGs with CRA, but damn I'm stuck and need your help.

I'm trying to do something like this:

const LoadIcon = (name) => lazy(() => import(`../icons/${name}.svg`));

const SvgComponent = ({ icon }) => {
  const Icon = LoadIcon(icon);
  console.log("Icon ", Icon);
  return <Icon />;
};

It's worth to mention that I did tried what official CRA suggest(without lazy load tho):

import { ReactComponent as Icon } from "../icons/myCoolSvg.svg";

But this kind of destructuring doesn't work with lazy.

Please help!

2 Answers

for destructing to work with lazy, you can default export it from separate file as below

// Middle Component
import { ReactComponent as Icon } from "./github.svg";

export default Icon;

and then call it lazily in your component

const MiddleComponent = lazy(() => import(`./MiddleComponent`));
const Svg = () => {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <MiddleComponent />
    </Suspense>
  );
};

Check demo here - https://codesandbox.io/s/react-lazy-svg-loading-gi2ru

Related