Last active
April 6, 2019 13:24
-
-
Save Nedson202/b51d1386d9b196677f45d0719c93d087 to your computer and use it in GitHub Desktop.
Image loader component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component, Fragment } from "react"; | |
import ImageLoader from "../ContentLoaders/ImageLoader"; | |
class ImageCard extends Component { | |
state = { | |
loadedErrorMessage: '', | |
imageUrl: '', | |
imageLoaded: false, | |
imageLoadError: false, | |
}; | |
renderLoaderAndSilentImage(data) { | |
const { image, size } = data; | |
const { imageLoaded, imageLoadError } = this.state; | |
/* Render the skeleton loader and hidden image loaded silently | |
only if the image has not been loaded and error is false */ | |
if (!imageLoaded && !imageLoadError) { | |
return ( | |
<Fragment> | |
<ImageLoader size={size} /> | |
<img | |
src={image || ''} | |
className="hide" | |
onLoad={this.imageRenderedStatus(image)} | |
onError={this.handleImageLoadError} | |
alt="userImage" | |
/> | |
</Fragment> | |
) | |
} | |
} | |
handleImageLoadError = () => { | |
this.setState({ | |
imageLoadError: true, | |
loadedErrorMessage: "Unable to fetch image", | |
imageLoaded: true, | |
}); | |
}; | |
imageRenderedStatus = image => () => { | |
this.setState({ | |
imageLoaded: true, | |
imageUrl: image, | |
}); | |
}; | |
renderImageOrError() { | |
const { loadedErrorMessage, imageUrl, imageLoadError, imageLoaded } = this.state; | |
if (imageLoaded && !imageLoadError) { | |
return ( | |
<img | |
src={imageUrl} | |
className="image" | |
alt="Random cap" | |
onLoad={this.imageRenderedStatus} | |
/> | |
) | |
} | |
if (imageLoadError) { | |
return ( | |
<span id="image-error-placeholder"> | |
<h1>{loadedErrorMessage}</h1> | |
<p id="error-symbol">!</p> | |
</span> | |
) | |
} | |
} | |
render() { | |
const { imageData } = this.props; | |
return ( | |
<div> | |
{this.renderLoaderAndSilentImage(imageData)} | |
{this.renderImageOrError()} | |
</div> | |
) | |
} | |
} | |
export default ImageCard; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment