Home > other >  React Native conditional render ImageBackground picture
React Native conditional render ImageBackground picture

Time:02-23

I am trying to set my image based on if my prop is not null. If my prop is not null I need to show image from a web link. If the prop is null then I need to show image from local file. What I am doing so far is not working

<ImageBackground
        source={{
            item.padStyle.icon !== null ? uri: 'https://example.com/image.png' : require('../../../assets/images/Hello.png'),
        }}
        style={styles.padImage}>
        <Text
          style={[
            styles.textBtnStyle,
            {
              color:
                item.padStyle.textColor !== null
                  ? item.padStyle.textColor
                  : colors.text,
            },
          ]}>
          {item.title}
        </Text>
      </ImageBackground>

CodePudding user response:

please try this way,

    <ImageBackground
              style={{height: 100, width: 100}}
              source={
                item.padStyle.icon !== null 
                  ? {uri: 'https://picsum.photos/200/300'}
                  : require('../../../assets/images/noImage.jpg')}>
</ImageBackground>

CodePudding user response:

Could you try this solution;

const imgSrc=item.padStyle.icon
?{uri:'https://example.com/image.png'}
:require('../../../assets/images/Hello.png');

return(
<ImageBackground
        source={imgSrc}
        style={styles.padImage}>
        <Text
          style={[
            styles.textBtnStyle,
            {
              color:
                item.padStyle.textColor !== null
                  ? item.padStyle.textColor
                  : colors.text,
            },
          ]}>
          {item.title}
        </Text>
      </ImageBackground>
);

  • Related