Last active
May 25, 2023 05:08
-
-
Save renesansz/8e2b78d67f9d9ba927d24dae708036d7 to your computer and use it in GitHub Desktop.
Lazy load SVG import in React + Vite
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import useLazyLoadSvg from "useLazyLoadSvg"; | |
function TestComponent () { | |
const { url, Icon } = useLazyLoadSvg(() => import("your-svg-path.svg")) | |
return ( | |
<img src={url} /> | |
<<Icon /> | |
) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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