Last active
February 22, 2021 09:32
-
-
Save shreyakupadhyay/5a9c4f6737a32cd30f82068566236981 to your computer and use it in GitHub Desktop.
Lazy loading 5 images stacked on a single scrollview in React-Native
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// lazy loading for three images | |
const ImageLazyLoad = React.forwardRef((props, ref) => { | |
const marker1 = React.useRef(null); | |
const marker2 = React.useRef(null); | |
const marker3 = React.useRef(null); | |
const [markerVisible, setmarkerVisible] = useState(0); | |
// marker Visible set with value -> 1,2,3 | |
React.useImperativeHandle(ref, () => ({ | |
onScroll: () => { | |
marker1 | |
&& marker1.current | |
&& marker1.current.measure((x, y, width, height, pageX, pageY) => { | |
if (pageY < heightWindow + 100 && markerVisible === 0) { | |
setmarkerVisible(1); | |
} | |
}); | |
marker2 | |
&& marker2.current | |
&& marker2.current.measure((x, y, width, height, pageX, pageY) => { | |
if (pageY < heightWindow + 100 && markerVisible === 1) { | |
setmarkerVisible(2); | |
} | |
}); | |
marker3 | |
&& marker3.current | |
&& marker3.current.measure((x, y, width, height, pageX, pageY) => { | |
if (pageY < heightWindow + 100 && markerVisible === 2) { | |
setmarkerVisible(3); | |
} | |
}); | |
}, | |
})); | |
const renderComponent = ( | |
<> | |
// your own image list | |
{[1,2,3].map((item) => { | |
return ( | |
<View | |
ref={ | |
item.key === 1 | |
? marker1 | |
: item.key === 2 | |
? marker2 | |
: item.key === 3 | |
? marker3 | |
: null | |
} | |
key={`${item.key}`} | |
onLayout={(event) => event.target.measure(() => {})} | |
> | |
<If condition={markerVisible >= item.key}> | |
<FastImage | |
source={{ | |
uri, // setup your own uri | |
priority: FastImage.priority.low, | |
}} | |
resizeMode={FastImage.resizeMode.cover} | |
/> | |
</If> | |
<If condition={markerVisible < item.key}> | |
<FastImage | |
resizeMode={FastImage.resizeMode.cover} | |
/> | |
</If> | |
</View> | |
); | |
})} | |
</> | |
); | |
return <>{renderComponent}</>; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment