Skip to content

Instantly share code, notes, and snippets.

@nwatab
Created August 17, 2020 00:20
Show Gist options
  • Save nwatab/7a0425f8d2f68a46820cca640410ead5 to your computer and use it in GitHub Desktop.
Save nwatab/7a0425f8d2f68a46820cca640410ead5 to your computer and use it in GitHub Desktop.
Lazy load image in Material-UI Card Media
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