16

When i use the Image component in React-native, it works fine when I declare my image's path/source as an inline string:

 <Image
    style={styles.img}
    source={require('mypic.png')}
 />

But when I define the path as a variable like this:

 var img = 'mypic.png';
 <Image
    style={styles.img}
    source={require(img)}
 />

...it doesn't work. The error msg is "Error: unknown named module 'mypic.png'"

I have many images, and I need to require them dynamically. There are too many to write manual import statements to require them one-by-one.

Even with a simple toggle like this one, it's far less efficient:

var icon = this.props.active ? require('./my-icon-active.png') : require('./my-icon-inactive.png');

How do people usually solve for dynamic loading of variable images?

1 Answer 1

23

You cannot do dynamic static images, so you can either use uri or do static things like var test=require('image'). Have a look at this issue: https://github.com/facebook/react-native/issues/2481

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.