Created
August 17, 2020 00:20
-
-
Save nwatab/7a0425f8d2f68a46820cca640410ead5 to your computer and use it in GitHub Desktop.
Lazy load image in Material-UI Card Media
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
import React, {useState, useEffect, useRef} from 'react' | |
import { CardMedia } from '@material-ui/core' | |
interface ICardMediaProp { | |
component: string, | |
image: string, | |
alt: string, | |
height: string, | |
} | |
export default (props: ICardMediaProp) => { | |
const [visible, setVisible] = useState<boolean>(false); | |
const placeholderRef = useRef<HTMLDivElement>(null); | |
useEffect(() => { | |
if (!visible && placeholderRef.current) { | |
const observer = new IntersectionObserver(([{ intersectionRatio }]) => { | |
if (intersectionRatio > 0) { | |
setVisible(true); | |
} | |
}); | |
observer.observe(placeholderRef.current); | |
return () => observer.disconnect(); | |
} | |
}, [visible, placeholderRef]); | |
return (visible | |
? | |
<CardMedia | |
component='img' | |
image={props.image} | |
alt={props.alt} | |
height={props.height} | |
/> | |
: | |
<div style={{height: props.height, backgroundColor: '#EEE'}} aria-label={props.alt} ref={placeholderRef} /> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment