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
Advertisement
Answer
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.