0

I need to place my state inside a string, as I am rendering an image depending on which 'type' state is.

I have tried Template literals below:

 constructor(props) {
 super(props);

 this.state = {
   type: 'cafe'
 }

And in my component:

 <Image
      source={require(        
 `../../../assets/icons/${this.state.type}.png`)}
 />

I would expect the outcome above to be:

 <Image
      source={require('../../../assets/icons/cafe.png')}
 />
kingloui
  • 161
  • 3
  • 12
  • The `require` needs to be static. You could possibly require both and then switch between what they resolve to. – zero298 Nov 04 '19 at 21:40
  • Does this answer your question? [React Native - Image Require Module using Dynamic Names](https://stackoverflow.com/questions/30854232/react-native-image-require-module-using-dynamic-names) – zero298 Nov 04 '19 at 21:40

1 Answers1

1

Using template literals with this.state should be fine for string interpolation but react-native's Image does not support dynamic paths for require. See the documentation at: https://facebook.github.io/react-native/docs/images

Instead you can require all the images at the module level and use the state to select the appropriate one.

const images = {
  cafe: require('../../../assets/icons/cafe.png'),
  // .. other images here
};

...

<Image source={images[this.state.type]} />
azundo
  • 5,902
  • 1
  • 14
  • 21