Skip to content

Commit

Permalink
Merge pull request #7 from Brykou/fix-loading
Browse files Browse the repository at this point in the history
Fix loading
  • Loading branch information
Brykou authored Oct 9, 2019
2 parents f93c8d4 + b688f73 commit 7752c43
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 15 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@binance-academy/fallback-image",
"version": "1.0.2",
"version": "1.0.3",
"description": "Display a fallback while an image is loading",
"main": "build/index.js",
"scripts": {
Expand Down
30 changes: 16 additions & 14 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,48 +19,50 @@ const imgStyle = {
transition: "opacity 1s linear",
};

class Image extends React.Component {
class ImageWithFallBack extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoaded: false,
};
}

componentDidMount() {
const { src } = this.props;
const image = new Image();
image.onload = () => {
this.setState({
isLoaded: true,
});
};
image.src = src;
}

render() {
const { src, alt, invertedRatio = 56.25, maxWidth, ...otherProps } = this.props;
const { isLoaded } = this.state;
return (
<div style={{ ...containterStyle, maxWidth: maxWidth || "auto" }} {...otherProps}>
<div style={{ ...placeholderStyle, paddingBottom: `${invertedRatio}%` }} />
<img
src={src}
alt={alt}
style={{ ...imgStyle, opacity: isLoaded ? 1 : 0 }}
onLoad={() => {
this.setState({
isLoaded: true,
});
}}
/>
<img src={isLoaded ? src : null} alt={alt} style={{ ...imgStyle, opacity: isLoaded ? 1 : 0 }} />
<noscript>{<img src={src} alt={alt} style={imgStyle} />}</noscript>
</div>
);
}
}

Image.propTypes = {
ImageWithFallBack.propTypes = {
/* Url of the image */
src: PropTypes.string.isRequired,

/* Alternative text to displayed if the image connot be loaded */
alt: PropTypes.string.isRequired,

/* Inverted ratio as a % (for a 16/9 ratio it's 9/16*100=56.25 for example) */
invertedRatio: PropTypes.string.isRequired,
invertedRatio: PropTypes.number.isRequired,

/* Provide an optional max width for the image */
maxWidth: PropTypes.string,
};

export default Image;
export default ImageWithFallBack;

0 comments on commit 7752c43

Please sign in to comment.