To make sure your styled component only appears once the image is fully loaded, create a wrapper around it.
One way to achieve this is by setting up a temporary image, waiting for it to load, and then notifying the component that the image is ready to 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>
);
};
Apply the wrapper in this manner:
<LazyBackgroundImage src="path/to/your-image.jpg">
<p>Greetings!</p>
</LazyBackgroundImage>