0
const BackgroundImage = styled.div`
  background: url(${(props) => props.backgroundImage}) no-repeat center center;
}

I use div in style component, but it has flickering issue waiting for the image to come in. Is there any lazy loading solution using styled-component's div?

Tina Glenn
  • 85
  • 6
  • 1
    Does this answer your question? https://stackoverflow.com/questions/43115246/how-to-detect-when-a-image-is-loaded-that-is-provided-via-props-and-change-sta – DSteman Jul 15 '22 at 12:41
  • @DSteman you gave an answer on img – Tina Glenn Jul 15 '22 at 12:44
  • But you can render this component conditionally in the same way. You want to wait for `props.backgroundImage` before rendering `BackgroundImage` right? – DSteman Jul 15 '22 at 12:50

1 Answers1

0

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>
Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32