Intentando cargar archivos SVG de forma dinámica, pero aparece un error de tiempo de ejecución y no estoy seguro de cuál es el problema. ¿Alguien puede ayudar?
Componente:
import React, { useEffect, useRef } from "react"; import { IIcon } from './IIcon'; import { DEFAULT_ASSET_ICON_FOLDER, } from '@/constants/default'; function Icon({name}: IIcon) { const ImportedIconRef = useRef(); useEffect(() => { const importIcon = async () => { try { ImportedIconRef.current = ( await import(`${DEFAULT_ASSET_ICON_FOLDER}/${name}.svg`) ).ReactComponent; } catch (err) { // @TODO - Log error somewhere } }; importIcon(); }, [name]); const SvgIcon = ImportedIconRef.current; return ( <SvgIcon /> ); } export default Icon;Uso: solo quiero pasar una referencia basada en cadenas al nombre del archivo.
<Icon name="DELETE" />Error Este es el error que estoy recibiendo, referirme a que el tipo de elemento no es válido
Unhandled Runtime Error Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. Check the render method of `Icon`.Está devolviendo un <SvgIcon /> nulo/indefinido mientras se carga el svg.
loading y actualícela en el bloque finally . const [, setLoading] = useState(false); useEffect(() => { setLoading(true); const importIcon = async () => { try { ImportedIconRef.current = ( await import(`./${DEFAULT_ASSET_ICON_FOLDER}/${name}.svg`) ).ReactComponent; } catch (err) { // @TODO - Log error somewhere // console.log(err); } finally { setLoading(false); } }; importIcon(); }, [name]); if (SvgIcon) { return <SvgIcon />; } return null;