Create a wrapper around your styled component which doesn't show the div
until the image is loaded.
You can accomplish this by creating an temporary image, wait for it to load, and then tell the component the image is ready and can be displayed.
const BackgroundImage = styled.div`
background: url(${(props) => props.backgroundImage}) no-repeat center center;
`;
const LazyBackgroundImage = ({ src, children }) => {
const [isLoaded, setIsLoaded] = useState(false);
useEffect(() => {
const image = new Image();
image.addEventListener('load', () => setIsLoaded(true));
image.src = src;
}, [src]);
if (!isLoaded) {
return null;
}
return (
<BackgroundImage backgroundImage={src}>
{children}
</BackgroundImage>
);
};
Use the wrapper like this:
<LazyBackgroundImage src="path/to/your-image.jpg">
<p>Hi there</p>
</LazyBackgroundImage>