Created
December 16, 2021 14:51
-
-
Save leonidkuznetsov18/c92f286367742aee3b0787aa17d7e48e to your computer and use it in GitHub Desktop.
react dynamic svg icon component
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
| 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