| 1 | import * as React from 'react'; |
| 2 | export 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 { |
nothing calls this directly
no test coverage detected
searching dependent graphs…