Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native images with dynamic names

This works no problem:

<Image source={require('./images/ace.png')} />

But this:

var name = 'ace';

<Image source={require('./images/' + name + '.png')} />

I've tried all kinds of variations but it always returns the error:

Requiring unknown module "./images/ace.png". If you are sure the module is there, try restarting the packager.

like image 396
Hasen Avatar asked Nov 27 '15 09:11

Hasen


People also ask

How do I add text to an image in react native?

If you want to add a text to an image you can use: react-native-media-editor. This is quite a good option for adding text to an image but I recommend you react-native-image-tools. It provides so much flexibility. You can add a text and position it accordingly.


1 Answers

As per react native docs,

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

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

How about pre-declaring what is required and use it conditionally?

like image 179
everlasto Avatar answered Sep 23 '22 16:09

everlasto