Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda