Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
41
rated 0 times [  43] [ 2]  / answers: 1 / hits: 99369  / 7 Years ago, thu, march 30, 2017, 12:00:00

I want to load a different image(fake avatar) while the final avatar image is loading. The idea is to detect when the prop image is loaded and change a state. Is it possible? Some ideas? Thank you!



class ImageUser extends React.Component {

constructor(props) {
super(props);
this.state = {userImageLoaded: false};
let imageSrc = ;

if (!this.props.userImage) {
imageSrc = this.props.noUserImage;
} else {
imageSrc = this.props.userImage;
}

this.loadingImage = <img className={styles.imageUser}
src={this.props.loadingImage} alt=2/>;

this.userImage =
<img onLoad={this.setState({userImageLoaded: true})}
className={styles.imageUser} src={imageSrc}
alt=1/>;

}

render() {
let image = ;
if (this.state.userImageLoaded) {
image = this.userImage;
} else {
image = this.loadingImage;
}
return (
<div>
{image}
</div>
);
}
}

export default ImageUser;

More From » image

 Answers
25

There are several ways to do this, but the simplest is to display the final image hidden, and then flip it to visible once it loads.



JSBin Demo



class Foo extends React.Component {
constructor(){
super();
this.state = {loaded: false};
}

render(){
return (
<div>
{this.state.loaded ? null :
<div
style={{
background: 'red',
height: '400px',
width: '400px',
}}
/>
}
<img
style={this.state.loaded ? {} : {display: 'none'}}
src={this.props.src}
onLoad={() => this.setState({loaded: true})}
/>
</div>
);
}
}

[#58330] Tuesday, March 28, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nathalieg

Total Points: 462
Total Questions: 106
Total Answers: 93

Location: Turks and Caicos Islands
Member since Tue, Mar 30, 2021
3 Years ago
;