Skip to content

Instantly share code, notes, and snippets.

@leonidkuznetsov18
Created December 16, 2021 14:51
Show Gist options
  • Select an option

  • Save leonidkuznetsov18/c92f286367742aee3b0787aa17d7e48e to your computer and use it in GitHub Desktop.

Select an option

Save leonidkuznetsov18/c92f286367742aee3b0787aa17d7e48e to your computer and use it in GitHub Desktop.
react dynamic svg icon component
export const Icon: React.FC<IconProps> = ({
name,
...rest
}): JSX.Element | null => {
const ImportedIconRef = React.useRef<
React.FC<React.SVGProps<SVGSVGElement>>
>();
const [loading, setLoading] = React.useState(false);
React.useEffect((): void => {
setLoading(true);
const importIcon = async (): Promise<void> => {
try {
ImportedIconRef.current = (
await import(`assets/icons/${name}.svg`)
).ReactComponent;
} catch (err) {
// Your own error handling logic, throwing error for the sake of
// simplicity
throw err;
} finally {
setLoading(false);
}
};
importIcon();
}, [name]);
if (!loading && ImportedIconRef.current) {
const { current: ImportedIcon } = ImportedIconRef;
return <ImportedIcon {...rest} />;
}
return null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment