Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda