Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
lazy loading for image in styled component
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?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

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>
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!