Created
November 4, 2021 12:05
-
-
Save audunolsen/48e1192c1f4db97a45626e4cd24770dc to your computer and use it in GitHub Desktop.
Dynamically import SVG files as React components
This file contains hidden or 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 React, { useState, useEffect } from "react"; | |
import { err } from "src/utils/async"; | |
interface Props extends React.SVGProps<SVGSVGElement> { | |
// path relative to src/assets/icons. omit svg extension | |
name: string; | |
} | |
interface Module { | |
default: React.FC<React.SVGProps<SVGSVGElement>>; | |
} | |
const Icon: React.FC<Props> = ({ name, ...props }) => { | |
const [module, setModule] = useState<Module>(); | |
async function importIcon() { | |
const md = (await import( | |
/* webpackMode: "eager" */ `src/assets/icons/${name}.svg` | |
).catch(err)) as Module; | |
if (md instanceof Error) { | |
console.error("Failed to load icon: " + md.message); | |
return; | |
} | |
setModule(md); | |
} | |
useEffect(() => { | |
void importIcon(); | |
}, []); | |
if (module?.default) { | |
const Icon = module.default; | |
return <Icon {...props} />; | |
} | |
return null; | |
}; | |
export default Icon; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment