@@ -40,15 +40,49 @@ const useImgix = (src: string) => {
40
40
} ;
41
41
} ;
42
42
43
- export const Img : React . FC < BoxProps & { loading ?: string ; src ?: string ; alt ?: string } > = ( {
44
- src : _src ,
45
- ...rest
46
- } ) => {
43
+ const getAspectRatio = dimensions => {
44
+ if ( ! dimensions ) return ;
45
+
46
+ const { width, height } = dimensions ;
47
+
48
+ return ( height / width ) * 100 ;
49
+ } ;
50
+
51
+ const BaseImg : React . FC < any > = props => (
52
+ < Box
53
+ loading = "lazy"
54
+ maxWidth = "100%"
55
+ width = { [ '100%' , '100%' , 'inherit' , 'inherit' ] }
56
+ display = "block"
57
+ as = "img"
58
+ { ...props }
59
+ />
60
+ ) ;
61
+
62
+ export const Img : React . FC <
63
+ BoxProps & { loading ?: string ; src ?: string ; alt ?: string ; dimensions ?: any }
64
+ > = React . memo ( ( { src : _src , dimensions, ...rest } ) => {
47
65
const { src, srcset } = useImgix ( _src ) ;
48
66
const props = {
49
67
src,
50
68
srcSet : srcset ,
51
69
...rest ,
52
70
} ;
53
- return < Box loading = "lazy" maxWidth = "100%" display = "block" as = "img" { ...props } /> ;
54
- } ;
71
+
72
+ if ( dimensions ) {
73
+ // means the image is local and we can generate the aspect ratio
74
+ // and prevent the page from jumping due to lack of an image being loaded
75
+ // (because of the built in lazy-loading)
76
+
77
+ const aspectRatio = getAspectRatio ( dimensions ) ;
78
+
79
+ const width = dimensions . width <= 720 ? dimensions . width : '100%' ;
80
+ return (
81
+ < Box width = { width } maxWidth = "100%" padding = "0 !important" position = "relative" className = "img" >
82
+ < Box height = "0" paddingBottom = { `${ aspectRatio } %` } width = "100%" />
83
+ < BaseImg position = "absolute" top = { 0 } left = { 0 } { ...props } />
84
+ </ Box >
85
+ ) ;
86
+ }
87
+ return < BaseImg className = "img" { ...props } /> ;
88
+ } ) ;
0 commit comments