Taylor Austin
Taylor Austin

Reputation: 6027

Why switching url src of image takes time to "load" in react?

I have a list of image urls in an array: const arr = [url1, url2, url3, url4, url5]. I loop through each of these and display all the images on a page. I also attach an onClick to the div they are in to switch the 'main' image to the side.

{arr.map(url => {
  return ( 
  <div onClick={() => this.setState({ imageUrl: url})}>
    <img src={url} alt=""/>
  </div> 
 );
})}

Then my main image is just: <img src={this.state.imageUrl} alt="" />

All this works just fine, but something weird is that when I click on one of the thumbnails to switch the main image. It seems to take some time to "load". I inspected the main image and the url is switch instantly so I am not sure why it seems to be "loading". Is this expected behavior or is it something else in my application?

Upvotes: 1

Views: 1221

Answers (1)

Fabio Lolli
Fabio Lolli

Reputation: 889

If that image is just a static url string, then when you assign it you're telling the img element to load the image from the url - so yes, unless it's already loaded in the page resources, it will take time to load.

If you were to import your image URL like import imageUrl from './whatever.png'; and assign that imported resource to the img src attribute, then the module to be considered loaded would first need to load the image - in this case the image will change immediately since the resource is already loaded.

When you import images like this, two things could happen: if the image is quite small, the variable gets assigned a dataURI, otherwise it gets assigned a regular url BUT that resource counts for the 'ready' trigger, so the effect is the same, image is immediately ready.

Does this make sense?

As far as I know this should be a standard React feature, but I've always been using ejected create-react-app projects - so it could be you need some webpack plugins to make this work - not sure about this.

Upvotes: 2

Related Questions