Michael Campsall
Michael Campsall

Reputation: 4335

How can I conditionally include images in React Native Component?

I am able to add static images to a ListView cell just fine (see code below), but how do I change the icon image dynamically?

From React Native Docs

<Image source={require('./img/check.png')} />

is the recommended way to reference image files for both iOS and Android.

I have a component called ExpandingCell that has the option to show a bunch of different icons but everything else remains the same.

In a ListView I create a cell object and then pass it into the ExpandingCell to render

the ListView data source array looks like this:

var LIST_DATA = [
 ...
  {type: 'ExpandingCell', 
   icon: './CellIcons/MagnifyingGlassIcon.png', //unused
   title: 'Lorem Ipsum', 
   detail: 'Donec id elit non mi porta gravida at eget metus.'},
...
];

then in renderCell method it gets passed the above cell object:

renderCell(cell) {
    if (cell.type === 'ExpandingCell') {
        return (
          <ExpandingCell cell={cell} />
        );
    }
}

Now in ExpandingCell I have this for render():

render() {
    return (
        ...
        <Image source{
            require('./CellIcons/MagnifyingGlassIcon.png')
        }>
        </Image>
        ...
    );
}

However, when I try to make use of this.props.cell.icon like this:

<Image source={require(this.props.cell.icon)}></Image>

I get the following error: Requiring unknown module "./CellIcons/MagnifyingGlassIcon.png".

Thanks in advance =)

Upvotes: 6

Views: 13792

Answers (2)

Chukwuebuka Nwoba
Chukwuebuka Nwoba

Reputation: 352

How to conditionally display either "require" or "uri" images in React Native Component 2022?

/** Displays Conditional Image Mapped from API */
  const randomFunction= () =>
    allData.map((fetchedData) => (
      <View key={fetchedData._id} style={styles.data}>
        <Image
          resizeMode="cover"
          source={
            fetchedData.avatar === ""
              ? require("../../assets/img/stationsImage.jpg")
              : { uri: `${fetchedData.avatar}` }
          }
          style={styles.imageStyling}
        />
    </View>
    ));

Hopefully this gives a different solution on how to conditionally render images from either require or uri sources in react native mobile apps.

Upvotes: 2

Daniel Basedow
Daniel Basedow

Reputation: 13396

The images have to be known during packaging. There's a section about it in the docs.

Put this at the top of the file you define ExpandingCell in:

const MAGNIFYING_GLASS_ICON = require('./CellIcons/MagnifyingGlassIcon.png');

Then you can use the constant like this

let icon = someCondition ? MAGNIFYING_GLASS_ICON : SOME_OTHER_ICON;
<Image source={icon}/>

You have to have the requires for all images you want to use this way in there.

Upvotes: 14

Related Questions