skip to Main Content

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


  1. afaik imports 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

    // map
    export const map = { brandOne: <SVG>, anotherBrand: <SVG> }
    
    // component
    const brand = await fetch('http://getbrand.com') // gets 'brandOne'
    
    return <CustomView>{map[brand]}</CustomView>
    
    Login or Signup to reply.
  2. 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:

    import React, { useState, useEffect } from 'react';
    import { SvgXml } from 'react-native-svg';
    
    const BrandLogo = ({ brand }) => {
      const [brandLogo, setBrandLogo] = useState(null);
    
      useEffect(() => {
        const loadComponent = async () => {
          try {
            const module = await import(`../../assets/svg/brand-logos/${brand}.svg`);
            setBrandLogo(module.default);
          } catch (err) {
            console.error(`Failed to load component: ${brand}`, err);
          }
        };
    
        loadComponent();
      }, [brand]);
    
      if (!brandLogo) {
        return null;
      }
    
      return <SvgXml xml={brandLogo} />;
    };
    
    export default BrandLogo;
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search