skillshot
skillshot

Reputation: 100

Render a component ONLY WHEN the image inside the component successfully loads

How can I delay the rendering of "My favorite image" (and the rest of the component) until the image successfully loads, which takes some time.

This is what I have attempted so far:

function ProjectCardView(props) {

    const [isImageLoaded, setIsImageLoaded] = useState(false)
    let imgTag = <img onLoad={() => {setIsImageLoaded(true)}} src={props.imgSrc}/>

    if (!isImageLoaded) {
        return <div></div>
    }

    return (
        <div>
            <h1> My favorite image </h1>
            {imgTag}
            
        </div>
    )
}

This issue with this attempt is that the whole component never appears.

Upvotes: 3

Views: 1793

Answers (1)

mc-user
mc-user

Reputation: 2071

You are rendering the component with the condition in this code.

if (!isImageLoaded) {
  return <div></div>
}

This will execute an empty div on the page. So you won't find anything on UI not even the img tag also. Your need to render the image first then only your state variables will get updated.

Check this sandbox. I am printing loading when the image is loading and loaded when it's done. Just update your conditions based on your image load time.

Edit mystifying-almeida-0lep2c

Upvotes: 2

Related Questions