Skip to content

Instantly share code, notes, and snippets.

@audunolsen
Created November 4, 2021 12:05
Show Gist options
  • Save audunolsen/48e1192c1f4db97a45626e4cd24770dc to your computer and use it in GitHub Desktop.
Save audunolsen/48e1192c1f4db97a45626e4cd24770dc to your computer and use it in GitHub Desktop.
Dynamically import SVG files as React components
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