react native render whole component when component image is loaded?

Viewed 331

I need to show the cards in app only when their images loaded successfully and if they are in loading state I want to show a loading indicator. so here's my implementation:


const [imageLoaded, setImageLoaded] = useState(false)

  const images = props.companyImages.map((el, index) => {
    return el.imageLink
  })

  const loaded = () => {
    setImageLoaded(true)
  }

  return (

      {!imageLoaded ? 

      <View style={styles.imageContainer}>
        <BitSwiper
          items={images.map((el, index) => index)}
          showPaginate={false}
          onItemRender={(item, index) => (
            <View key={index} style={{ height: 200, overflow: 'hidden', borderTopRightRadius: 20, borderTopLeftRadius: 20 }}>
              <Image
                source={{ uri: images[index] }}
                style={{ width: '100%', height: '100%', overflow: 'hidden' }}
                onLoad={loaded}
              />
            </View>
          )}
        />
      </View>
        :
        <ActivityIndicator color='red' /> 
}

but this doesn't work. any ideas?

1 Answers
<View style={styles.imageContainer}>
  <BitSwiper
    items={images.map((el, index) => index)}
    showPaginate={false}
    onItemRender={(item, index) => (
      <View key={index} style={{ height: 200, overflow: 'hidden', borderTopRightRadius: 20, borderTopLeftRadius: 20 }}>
        <Image
          source={{ uri: images[index] }}
          style={{ width: '100%', height: '100%', overflow: 'hidden',opacity: imageLoaded?1:0}}
          onLoad={loaded}
        />
        {!imageLoaded? <ActivityIndicator color='red' /> :<></>}
      </View>
    )}
  />
</View>
  

wrap ActivityIndicator in an absolute positioned container and center it, you can add a transition to image fade if you want

also, i'm not sure about the opacity, if it's meant to be used in styles, but you'll find the way :)

Related