Reputation: 1503
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
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.
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
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