Skip to content

Require non-static image in React Native

I have a special folder with images in my React Native application. Path to these pictures is stored in the special object that is passed as prop to the Card component. So, I can’t use require, because it uses only static path string. How can I use load these images from my props? There is my try:

import React from 'react';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  StyleSheet
} from 'react-native';
import EmptyImage from '../data/images/empty-image.jpg';
class Card extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    const { myObject } = this.props;
    return (
    <View>
        <Image
           source={
               myObject.imagesNames[0] ?
                  require(`../data/images/${myObject.imagesNames[0]}`)
               :
                  EmptyImage
            }
         />
    </View>
    );
  }
}
export default Card;

Answer

As your images are local better create a json object by requiring the images like below

images={
  image1:require('path'),
  image2:require('path2'),
};

And you can set the url like below

<Image source={
               myObject.imagesNames[0] ?images[imagesNames[0]]:EmptyImage
            }
         />