Using display none instead of condition state rendering

Viewed 38152

I m trying to use conditional rendering (in this specific case) that would allow me to make something like :

<Image
    source={{ uri: "https://images4.alphacoders.com/221/221716.jpg" }}
    style={this.state.isLoaded ? styles.loaded : { display: "none" }}
    onLoadEnd={() => {
    console.log("test"), this.setState({ isLoaded: true });
    }}
/>

The main problem is that React Native doesn't seem to be able to use its internal lifecycle functions when the display: none style is used, and thus doesn't call onLoadEnd. It doesn't log anything.

I don't have any idea how to encounter this problem while using display style props

3 Answers

Next time, it would be super cool if you setup a snack to demo your issue.

This pattern will work for you...

<Image
  source={{ uri: "https://images4.alphacoders.com/221/221716.jpg" }}
  style={[{width: 0, height: 0,},
  this.state.isLoaded && {width: 400, height: 400,}]}
  resizeMode="contain"
  onLoadEnd={() => {
    this.setState({ isLoaded: true });
  }}
/>

I've created a demo on snack for you

update with display: none

<Image
  source={{ uri: "https://images4.alphacoders.com/221/221716.jpg" }}
  style={[{width: 400, height: 400,},
  !this.state.isLoaded && {display: 'none'}]}
  resizeMode="contain"
  onLoadEnd={() => {
    this.setState({ isLoaded: true });
  }}
/>

I tried various things, but finally style: {height: 0, width: 0, opacity: 0} worked for me.

Related