Home > database >  Conditional rendering of svg files in react native
Conditional rendering of svg files in react native

Time:12-15

I have an app for buying and selling dogs. In my app each dog breed has its own svg file stored in my assets folder (around 150 svg files). When fetching post data from the backend, I get different information about a the post, including the dogBreed, e.g. {dogBreed: golden-retriver}. I want to render the corresponding svg to each post of dogs, but I am unsure about what the best way to deal with this is. Should my app import all svg files? Should I convert all the svg files into JSX files? I have done this in other parts of the application. If i'm going for the JSX solution, should I render the JSX conditionally based on the name like: <${dogBreed}/> (if it is possible), or should I have one component take in the dog breed as a prop and have logic within for conditional rendering? . This would create a huge file, and I'm not sure if 150 if else/switch statements is the way to go. I feel really stuck here.

CodePudding user response:

First of all, converting all of your svg file to react native JSX files.

Then you can lazy load the svg based on name (I assume) Something like

const breedName = data.dogBreed;    
const component = React.lazy(() => import(`./assets/${breedName}.jsx`));

CodePudding user response:

I recommend you to use react-native-svg-transformer library.

Here's the link to the library: https://github.com/kristerkari/react-native-svg-transformer This library allows you to import the svg files without converting them.

After the configuration you can do similar to this.

...
import LogoA from "./logo_a.svg";
import LogoB from "./logo_b.svg";
...

return cond ? <LogoA width={120} height={40} /> : <LogoB width={120} height={40} />

...
  • Related