简体   繁体   中英

Conditional rendering of svg files in react native

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, eg {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.

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`));

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} />

...

Try using this library https://github.com/stowball/react-native-svg-icon . Convert all the svgs to JSX in one file.

Create an component as a bridge between react-native-svg-icon's which imports the above SVGs

you can directly use this as component.

import Icon from './components/Icon';

// Inside some view component
render() {
  return (
    <Fragment>
      <Icon name="SortArrows" height="20" width="20" />
      <Icon name="Tick" fill="#0f0" viewBox="0 0 200 200" />
      <Icon name="Star" fill="transparent" stroke="#fff" strokeWidth="5" 
  />
    </Fragment>
 );
}

you can place name as dynamic to render dynamic svg icon. Just give it a try.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM