-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathImg.tsx
More file actions
63 lines (54 loc) · 1.78 KB
/
Img.tsx
File metadata and controls
63 lines (54 loc) · 1.78 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
import React, {forwardRef, JSX} from 'react'
import useImage, {useImageProps} from './useImage'
import imagePromiseFactory from './imagePromiseFactory'
export type ImgProps = Omit<
React.DetailedHTMLProps<
React.ImgHTMLAttributes<HTMLImageElement>,
HTMLImageElement
>,
'src'
> &
Omit<useImageProps, 'srcList'> & {
src: useImageProps['srcList'] // same types, different name
loader?: JSX.Element | null
unloader?: JSX.Element | null
decode?: boolean
crossorigin?: string
container?: (children: React.ReactNode) => JSX.Element
loaderContainer?: (children: React.ReactNode) => JSX.Element
unloaderContainer?: (children: React.ReactNode) => JSX.Element
}
const passthroughContainer = (x) => x
function Img(
{
decode = true,
src: srcList = [],
loader = null,
unloader = null,
container = passthroughContainer,
loaderContainer = passthroughContainer,
unloaderContainer = passthroughContainer,
imgPromise,
crossorigin,
useSuspense = false,
...imgProps // anything else will be passed to the <img> element
}: ImgProps,
ref,
): JSX.Element | null {
imgPromise =
imgPromise || imagePromiseFactory({decode, crossOrigin: crossorigin})
const {src, isLoading} = useImage({
srcList,
imgPromise,
useSuspense,
})
// console.log({src, isLoading, resolvedSrc, useSuspense})
// show img if loaded
if (src) return container(<img src={src} {...imgProps} ref={ref} />)
// show loader if we have one and were still trying to load image
if (!useSuspense && isLoading) return loaderContainer(loader)
// show unloader if we have one and we have no more work to do
if (!useSuspense && unloader) return unloaderContainer(unloader)
return null
}
export default forwardRef<HTMLImageElement, ImgProps>(Img)