tajji
tajji

Reputation: 465

Previous image stays while the next is loading

A quick demo: Codesandbox link

Notice that when the image is switched, text related to the next image appears right away, but as the next image loads, the previous one stays there until the next one hasn't fully loaded.

Initially, the user sees:

Text 1
[             ]
[    Image1   ]
[             ]

On switching, the next image takes some time to load, so the user sees

Text 2
[             ]
[    Image1   ]
[             ]

and then,

Text 2
[             ]
[    Image2   ]
[             ]

Ideally, I'd like to clear the previous image while the next one is loading. Is there a way to do this? That is, while the next image is loading, the user should seee

Text 2
[             ]
[             ]
[             ]

Obviously, this only happens the first time an image is loaded. After an image is fetched (and I guess stored in session cache or something), there is no delay when the images are switched.

Upvotes: 3

Views: 1495

Answers (4)

Dylan I
Dylan I

Reputation: 186

If anyone is looking for an alternative solution, setting the key property on the img tag to a value unique to each image worked for me

Upvotes: 1

Mohammad Salim Hosen
Mohammad Salim Hosen

Reputation: 303

You can take another state variable

  const [show, setShow] = useState(false);

Then Change your handleImageSwitch function to this

const handleImageSwitch = () => {
    setShow(false);
    item === 0 ? setItem(1) : setItem(0);
  };

Change Your Image Tag to this

<img
  onLoad={() => setShow(true)}
  style={{
    maxWidth: "200px",
    display: show ? "block" : "none",
    margin: "0 auto"
  }}
  src={images[item].url}
  alt=""
/>

Check my Sandbox: https://codesandbox.io/s/affectionate-goldwasser-fbr3c?file=/src/App.js

Upvotes: 2

BTSM
BTSM

Reputation: 1663

Try like this.

<div style={{ minHeight: "100px" }}>
      {item===0 && <img style={{ maxWidth: "200px" }} src={images[0].url} alt="" />}
      {item===1 && <img style={{ maxWidth: "200px" }} src={images[1].url} alt="" /> }
</div>

You can confrim here.

https://codesandbox.io/s/modest-poitras-4ttp0?file=/src/Carousel.js:598-669

Upvotes: 0

Kuldeep Bora
Kuldeep Bora

Reputation: 4882

It takes time to fetch image. you can put images in state (useState([]) and fetch images in useEffect hook or a function and use a loading state. before fetching image, set loading to true. When loading is true, you can show blank or anything in place of image. This way you only have to fetch image once.

Upvotes: 0

Related Questions