Rizwan Ahmed Shivalli
Rizwan Ahmed Shivalli

Reputation: 1503

Importing multiple SVG via name in a react-native component

I am trying to fetch multiple icons from assets/Icons folder where I have placed multiple icons as svgs I want to load the svg by passing name.

I am able to get the icon by

import CustomIcon from '../assets/Icons/icon-account.svg';

<View>
    <CustomIcon/>
</View>

but i can't keep writing multiple imports for each and every icon I need.

is there a way I can get the required icons by passing name as a prop to

example

import CustomIcon from '../assets/Icons';

<View>
    <CustomIcon name='icon-account.svg'/>
</View>

Is there anyway so that I can get the above code working?

Upvotes: 2

Views: 5325

Answers (2)

Onur Eker
Onur Eker

Reputation: 940

If you are looking to conditionally render a .svg file by passing a prop to the component, you can do this:

Let's say you have a few flags and you'd like to render svg images given the country name.

  1. Import all flags to a file called flags.js, create a flags object so you can pass keys to your Flag component; and a Flag component to import later on:
import React from 'react';
import Austria from '../../assets/NationalTeams/austria.svg';
import Belgium from '../../assets/NationalTeams/belgium.svg';
import Croatia from '../../assets/NationalTeams/croatia.svg';
...

const flags = {
  Austria: Austria,
  Belgium: Belgium,
  Croatia: Croatia,
  ...
}

// See: https://reactjs.org/docs/jsx-in-depth.html#choosing-the-type-at-runtime

export default function Flag(props) {
  const CountryFlag = flags[props.country];
  return <CountryFlag width={30} height={30} />;
}

2.Then import this component whenever you need to render a .svg image and pass the country prop as defined in flags object.

import Flag from '../../Flag.js';

...
// will render Austria flag
<Flag country={'Austria'} /> 
...

Upvotes: 2

TKoL
TKoL

Reputation: 13912

Why don't you import them all into a central file

import AccountIcon from '../assets/Icons/icon-account.svg';
import GearIcon from '../assets/Icons/icon-gear.svg';

export default { 
    AccountIcon,
    GearIcon
}

And then import that central file elsewhere?

Upvotes: 3

Related Questions