Skip to content

Instantly share code, notes, and snippets.

@renesansz
Last active May 25, 2023 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renesansz/8e2b78d67f9d9ba927d24dae708036d7 to your computer and use it in GitHub Desktop.
Save renesansz/8e2b78d67f9d9ba927d24dae708036d7 to your computer and use it in GitHub Desktop.
Lazy load SVG import in React + Vite
import useLazyLoadSvg from "useLazyLoadSvg";
function TestComponent () {
const { url, Icon } = useLazyLoadSvg(() => import("your-svg-path.svg"))
return (
<img src={url} />
<<Icon />
)
}
import { FunctionComponent, useState } from "react";
type SvgRef = {
default: string;
ReactComponent: FunctionComponent<any>;
};
function lazyLoadFile(factory: () => Promise<SvgRef>) {
return () => factory().then((res) => res);
}
// NOTE: Placeholder component to prevent build error.
const PlaceholderComponent = () => <></>;
export default function useLazyLoadSvg(factory: () => Promise<SvgRef>) {
const [url, setUrl] = useState("");
const [Icon, setIcon] = useState<FunctionComponent<SVGElement> | JSX.Element>(
() => PlaceholderComponent
);
const svgData = lazyLoadFile(factory);
svgData()
.then((result) => {
setUrl(result.default);
setIcon(result.ReactComponent);
})
.catch((err) => {
console.error(err);
});
return {
url,
Icon,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment