0

I am using react native and I have tried two pieces of code, the first one does not work and the second one does. Can anyone explain why?

  1. <Image source={require('../assets/'+'g'+'Light.png')} style={styles.greenLight}/>
  2. <Image source={require('../assets/gLight.png')}
2
  • Not sure why, but I've had a similar issue. I solved it by passing a function that concatenates the string into the image source require statement. Commented Dec 2, 2015 at 22:51
  • This is so frustrating. If I understand correctly, passing an array with images names and concatenating them to the correct relative path is not possible? This is possible in almost any modern programming language (and old as far as I know). Commented May 6, 2017 at 12:25

1 Answer 1

2

Using dynamic naming in React Native is not allowed. You should use a switch, if statement or a different function which will do this for you:

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

// 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} />

More information here: https://facebook.github.io/react-native/docs/images.html

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.