After I make an API call I receive a motorbike brand name and I need to display its logo accordingly. The logos are SVGs that I have converted to JSX using react-native-svg
. How would I go about doing such a thing ?
After asking chatGPT I have tried this :
const [BrandLogo, setBrandLogo] = useState(null);
useEffect(() => {
const loadComponent = async () => {
try {
const module = await import(`../../assets/svg/brand-logos/${brand}`);
setBrandLogo(() => module.default);
} catch (err) {
console.error(`Failed to load component: ${brand}`, err);
}
};
loadComponent();
}, [brand]);
It does not seem to be working unfortunately
2
Answers
afaik
import
s happen at build time, so trying to import dynamically here wont work at all. try to create an object map of all SVGs and match the brand to the right key.pseudo code
It looks like you are on the right track. However, I notice that you are using a function to set the state of BrandLogo. Instead, you can directly set the state to the loaded module.
Here’s the modified code that should work:
In this modified code, I have added the SvgXml component from react-native-svg to display the loaded SVG logo. I have also made the following changes:
Renamed BrandLogo to BrandLogoComponent to avoid conflicts with the brandLogo state variable.
Directly set the state of brandLogo to the loaded module.
Added a check for brandLogo before rendering the SvgXml component. If brandLogo is null, we return null to prevent rendering anything.
Changed the import statement to include the .svg extension. This is necessary for dynamic imports to work with SVG files.