I have a string that is the name of the icon I want to import/require and I'm trying to import/require the SVG file that I want to use in React Native dynamically. My initial idea was this:
const icon = require(`@src/assets/icons/${iconName}`)
However, I realized that this would not work and that I need to have all my icon options imported. This is why I created an Icons.ts file from which I'm trying to require and then export all my icons like this:
const Icons = {
ArrowRight: import('@src/assets/icons/ArrowRight.svg'),
ArrowLeft: import('@src/assets/icons/ArrowLeft.svg'),
};
export default Icons;
And then I attempted to use them in my component like by hardcoding Icons.ArrowRight:
{leftIcon && <IconContainer>{Icons.ArrowRight}</IconContainer>}
Which unfortunately didn't work and I got the following error:
Objects are not valid as a React child.
If I import an icon straight in my component like this:
import Close from '@src/assets/icons/close.svg';
I can then use it like this:
<Close />
You need to execute the icon component.
<IconContainer><Icons.ArrowRight /></IconContainer>}