Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a default image on load of the page, then overwrites it

I have a page which contains several images. When the page loads it provides a default image for each IMG:

import default from './pics/default.jpg';

<img src={default} alt="#"/>

What I want is something like this:

<img src1={default} src2="img url" alt="#"/>

Where src2 overwrites src1 when it is loaded.

Edit: The first image (src1) comes as the page loads while the second (src2) is requested trough the internet. Example: https://cdn.pixabay.com/photo/2016/10/17/10/52/wind-farm-1747331__340.jpg

like image 690
Laczkó Örs Avatar asked Aug 30 '19 15:08

Laczkó Örs


2 Answers

Use the onLoad event on your <img> element. You can give it a display: none style until it finishes loading.

class ImageRoll extends React.Component {
  state = {loaded: false};
  
  showImage = () => {
    this.setState({loaded: true});
  }
  
  render() {
    return (
      <>
        <img src="/path-to-initial" style={ this.state.loaded ? {display: "none"} : {}} />
        <img src="/path-to-seocndary" onLoad={this.showImage} style={ this.state.loaded ? {} : {display: "none"}} />
      </>
    );
  }
}

Edit: As opposed to the other answers, the reason we want to do this is that replacing the src on an image is actually bad practice. If you want to roll an image it is better to have two <img> elements and toggle between them depending on conditions.

like image 65
Chase Avatar answered Nov 04 '22 07:11

Chase


You can just update directly the src of the image, I have a sample on Code Sandbox.

This is the content:

function App() {
  const [imageSrc, setImageSrc] = React.useState("/placeholder.jpg");

  function loadImage() {
    setImageSrc(`https://picsum.photos/200?${Date.now()}`);
  }

  return (
    <div className="App">
      <div>
        <img alt="small-image" src={imageSrc} />
      </div>
      <div>
        <button onClick={loadImage}>Load Image!</button>
      </div>
    </div>
  );
}

This is just a basic example, you can implement your own logic. Hope this helps!

like image 24
Jojo Tutor Avatar answered Nov 04 '22 07:11

Jojo Tutor