In my application I got 8 svg files which I want to import dynamically. I have tried the following:
First I created a Floor component that has one name prop. This is the name of the floor that the user wants to see. In my dynamic import, the path to the svg is specified but it always seems to return undefined.
I know the path to the svg is correct because if I fill in a wrong path, React complains it can't find the svg file.
import React, { useEffect, useState } from "react";
const Floor = ({ name }) => {
const [floor, setFloor] = useState(null);
useEffect(() => {
/*
This is where it goes wrong. If I log the result It shows 'undefined'.
*/
import(`./floors/${name}.svg`)
.then((module) => {
setFloor(module);
})
.catch((error) => {
console.error(`Icon with name: ${name} not found!`);
});
}, [name]);
const renderFloor = () => {
if (!floor) return null;
const Floor = floor.ReactComponent;
return <Floor />;
};
return <>{renderFloor()}</>;
}
export default Floor;
And this is how I import the Floor
import Floor from './Floor'
const Floorplan = () => {
return (
<Floor name="floor-4" />
)
}
export default Floorplan;
I have found something similar but I still have the same error 'undefined'
These are the errors Im getting.
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.
And if I log the dynamic import response:
Object { loaded: Getter, id: Getter, exports: undefined, webpackPolyfill: 1 } Icon.js:14