/
on-load.js
101 lines (92 loc) · 2.33 KB
/
on-load.js
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { useState } from 'react'
import Image from 'next/image'
const Page = () => {
// Hoisted state to count each image load callback
const [idToCount, setIdToCount] = useState({})
const [clicked, setClicked] = useState(false)
return (
<div>
<h1>Test onLoad</h1>
<p>
This is the native onLoad which doesn't work as many places as
onLoadingComplete
</p>
<ImageWithMessage
id="1"
src="/test.jpg"
layout="intrinsic"
width="128"
height="128"
idToCount={idToCount}
setIdToCount={setIdToCount}
/>
<ImageWithMessage
id="2"
src={require('../public/test.png')}
placeholder="blur"
layout="fixed"
idToCount={idToCount}
setIdToCount={setIdToCount}
/>
<ImageWithMessage
id="3"
src="/test.svg"
layout="responsive"
width="1200"
height="1200"
idToCount={idToCount}
setIdToCount={setIdToCount}
/>
<ImageWithMessage
id="4"
src="/test.ico"
layout="fill"
objectFit="contain"
idToCount={idToCount}
setIdToCount={setIdToCount}
/>
<ImageWithMessage
id="8"
src={clicked ? '/foo/test-rect.jpg' : '/wide.png'}
layout={clicked ? 'fixed' : 'intrinsic'}
width="500"
height="500"
idToCount={idToCount}
setIdToCount={setIdToCount}
/>
<button id="toggle" onClick={() => setClicked(!clicked)}>
Toggle
</button>
<div id="footer" />
</div>
)
}
function ImageWithMessage({ id, idToCount, setIdToCount, ...props }) {
const [msg, setMsg] = useState('[LOADING]')
const style =
props.layout === 'fill'
? { position: 'relative', width: '64px', height: '64px' }
: {}
return (
<>
<div className="wrap" style={style}>
<Image
id={`img${id}`}
onLoad={(e) => {
let count = idToCount[id] || 0
count++
idToCount[id] = count
setIdToCount(idToCount)
const msg = `loaded ${count} ${e.target.id} with native onLoad`
setMsg(msg)
console.log(msg)
}}
{...props}
/>
</div>
<p id={`msg${id}`}>{msg}</p>
<hr />
</>
)
}
export default Page