How to check an image is loaded in a Skeleton functionality workflow in React

Viewed 1894

I am implementing a Skeleton for a Card component as such:

{ loadingContext & <MySkeleton/> : <Card/> }

However, for this to truly work properly, I need to test for the image within the Card component to finish loading through something like:

<img onload={() => setLoadingContext(false)} .../>

But, this Card component code doesn't get called until loading is set to false, and the code that sets loadingContext to false is in the Card component. A negative infinite loop if you like.

The question is, then, how do I effectively check that the Card component's image has completely loaded in this situation?

Cheers, Matt

2 Answers

First, what's the purpose of handling loading outside of the card component?

Second, if I would do it, I would make a component with Image and skeleton in it, Put image and skeleton inside a view, and set skeleton position to absolute, rather than this condition, until image is not loaded, I will keep showing skeleton on top of Image. Hope you got it.

function ImageWithLoad(props) {

   return (
      <View>
         loadingContext && <Skeleton style={styles.absolute} />
         <Image  onload={() => setLoadingContext(false)}>
      </View>
   );
}

export default ImageWithLoad;

One solution is to load both components and use the loading state/context to control what is displayed through CSS. This way, we can access the onLoad event on the img tag in the Card component (styles attached to the component for demonstration purposes)

function Post() {
    ...
    return (
        <>
            <Skeleton style={{display: loadingContext ? "block" : "none"}}/>
            <Card style={{display: loadingContext ? "none" : "block"}}/>
        </>

    )
}

In the Card component we have an image. When this is loaded we set the loading state or context to false

<img onLoad={() => setLoadingContext(false)} ... />
Related