From 92bdc1acf687eed701bb780d411f6a0c514437a5 Mon Sep 17 00:00:00 2001 From: Ariful Alam Date: Sat, 19 Mar 2022 00:53:20 +0600 Subject: [PATCH] Create LazyImage component --- src/components/lazy-image/index.jsx | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/components/lazy-image/index.jsx diff --git a/src/components/lazy-image/index.jsx b/src/components/lazy-image/index.jsx new file mode 100644 index 0000000..5c54f7d --- /dev/null +++ b/src/components/lazy-image/index.jsx @@ -0,0 +1,22 @@ +import { useState, Fragment, useEffect } from 'react'; + +const LazyImage = ({ placeholder, src, alt, ...rest }) => { + const [loading, setLoading] = useState(true); + + useEffect(() => { + const imageToLoad = new Image(); + imageToLoad.src = src; + + imageToLoad.onload = () => { + setLoading(false); + }; + }, [src]); + + return ( + + {loading ? placeholder : {alt}} + + ); +}; + +export default LazyImage;