I am creating a custom category component that will load all of my SVGs listed in an object.
import { type SvgProps } from 'react-native-svg';
import FoodAndDrink from './icon-svgs/food-and-drink.svg';
import TransportOrFuel from './icon-svgs/transport-or-fuel.svg';
const Svgs = {
foodAndDrink: FoodAndDrink,
transportOrFueld: TransportOrFuel,
};
export type CategoryIconProps = {
name: keyof typeof Svgs;
size?: number;
};
export const CategoryIcon = ({ name, size, ...props }: SvgProps & CategoryIconProps) => {
const Component = Svgs[name];
return <Component {...(size && { width: size, height: size })} {...props} />;
};
This will work well. But i'm worried that as my Svg list grows. It will starting to hurt the performance since even though i'm only selecting one svg like this.
<CategoryIcon name="foodAndDrink" size={horizontalScale(32)} />
All the other svgs that aren't being used are still being loaded.
Is there a better approach to work around this so that only the selected SVGs are being loaded?
I have tried to use dynamic import but it expected to be not worked since we need to turn the react-native component into async like this
export const CategoryIcon = async ({ name, size, ...props }: SvgProps & CategoryIconProps) => {
const Svgs = {
foodAndDrink: (await import('./icon-svgs/food-and-drink.svg')).default,
// ... define other SVGs similarly
};
const Component = Svgs[name];
return <Component {...(size && { width: size, height: size })} {...props} />;
};