Open History to see the last commit
1import * as React from 'react';
2export class ProgressiveImage extends React.Component {
3 constructor(props) {
4 super(props);
5 this.state = {
6 image: props.placeholder,
7 isLoading: true
8 };
9 }
10β
11 componentDidMount() {
12 const {
13 src
14 } = this.props;
15β
16 if (src) {
17 this.loadImage(src);
18 }
19 }
20β
21 componentDidUpdate(prevProps) {
22 const {
23 src,
24 placeholder
25 } = prevProps; // We only invalidate the current image if the src has changed.
26β
27 if (src && src !== this.props.src) {
28 this.setState({
29 image: placeholder,
30 isLoading: true
31 }, () => {
32 this.loadImage(src);
33 });
34 }
35 }
36β
37 componentWillUnmount() {
38 if (this.image) {
39 this.image.onload = null;
40 this.image.onerror = null;
41 }
42 }
43β
44 loadImage = src => {
45 // If there is already an image we nullify the onload
46 // and onerror props so it does not incorrectly set state
47 // when it resolves
48 if (this.image) {
49 this.image.onload = null;
50 this.image.onerror = null;
51 }
52β
53 const image = new Image();
54 this.image = image;
55 image.onload = this.onLoad;
56 image.onerror = this.onError;
57 image.src = src;
58 };
59 onLoad = () => {
60 const {
61 naturalWidth,
62 naturalHeight
63 } = this.image; // use this.image.src instead of this.props.src to
64 // avoid the possibility of props being updated and the
65 // new imageisLoading before the new props are available as
66 // this.props.
67β
68 this.setState({
69 naturalHeight,
70 naturalWidth,
71 aspectRatio: naturalHeight / naturalWidth,
72 orientation: naturalWidth > naturalHeight ? 'landscape' : 'portrait',
73 image: this.image.src,
74 isLoading: false
75 });
76 };
77 onError = errorEvent => {
78 const {
79 onError
80 } = this.props;
81β
82 if (onError) {
83 onError(errorEvent);
84 }
85 };
86β
87 render() {
88 const {
89 children
90 } = this.props;
91β
92 if (!children || typeof children !== 'function') {
93 throw new Error(`ProgressiveImage requires a function as its only child`);
94 }
95β
96 return children(this.state);
97 }
98β
99}