Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require Image dynamically in React Native

The documentation of React native (0.21) states, that it is only possible, to load pictures statically, i.e. if the file name is somehow known in advance:

Note that in order for this to work, the image name in require has to be known statically.

Source: https://facebook.github.io/react-native/docs/images.html#content

An example is given:

// GOOD
<Image source={require('./my-icon.png')} />

// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />

Unfortunately, in my case, I do not know the file names of the pictures in advance, as they are configured in a JSON file.

Is there a way to use local image files within react native? I could load them via the file:// protocol, if I knew the location of the files? Is there a constant or variable for he location of the app within the iOS file system?

like image 380
Rias Avatar asked Oct 30 '25 13:10

Rias


1 Answers

Yes, you can use images dynamically. They're treated, however, as network images. What this means is that the packager didn't attach any image metadata (width, height).

If you've a few images, simply leverage the packager.

// GOOD
var icon = this.props.active ? require('./my-icon-active.png') : require('./my-icon-inactive.png');
<Image source={icon} />

The other option is to save metadata (width, height) in your JSON. You'll need to specify at least the height for network images (or dynamic images). Given the metadata(width, height) and screen dimensions using (React.Dimensions), it's trivial to select appropriate height. Use react-native-orientation if your app needs to work in portrait and landscape mode.

like image 166
nmh Avatar answered Nov 02 '25 02:11

nmh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!