Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
84 lines (76 loc) · 1.77 KB
/
Copy pathindex.js
File metadata and controls
84 lines (76 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import React from 'react' // Can be aliased to Preact in your project
export class Image extends React.Component {
constructor (props) {
super(props)
this.state = {
loaded: -1 // index of loaded src
}
this._imgs = []
this._loadImage = this._loadImage.bind(this)
}
_loadImage (idx, src) {
if (typeof document !== 'undefined') {
const img = document.createElement('img')
this._imgs.push(img)
img.onload = () => {
if (this.state.loaded < idx) {
this.setState({ loaded: idx })
}
this._removeImage(img)
}
img.onerror = () => {
console.warn(`Failed to load srcs[${idx}] => ${src}`)
this._removeImage(img)
}
img.src = src
}
}
_removeImage (img) {
if (img) {
img.remove()
}
if ((this._imgs || []).includes(img)) {
this._imgs = this._imgs.filter(i => i !== img)
}
}
componentDidMount () {
const { srcs } = this.props
if (srcs && srcs.length > 0) {
for (let x = 0; x < srcs.length; x++) {
this._loadImage(x, srcs[x])
}
}
}
componentWillUnmount () {
if (this._imgs && this._imgs.length > 0) {
for (let x = 0; x < this._imgs.length; x++) {
this._removeImage(this._imgs[x])
}
}
}
render () {
const {
srcs,
unloadedSrc = '/images/blank-poster.gif',
className,
...props
} = this.props
const { loaded } = this.state
return loaded === -1
? (
<img
src={unloadedSrc}
className={`${className} image-loading`}
{...props}
/>
)
: (
<img
src={srcs[loaded]}
className={`${className} image-ready`}
{...props}
/>
)
}
}
export default Image