Search code examples
javascriptreactjslazy-loading

How to Lazy load the background image inside the inline style property (React)?


I'm currently working on my first React app, and I'm facing something tough (for me).

<div
    className="container-fluid"
    id="cityDetail"
    style={{
        backgroundImage: `url(${camera.lastPhoto})`,
        backgroundRepeat: "no-repeat",
        backgroundPosition: "center",
        backgroundSize: "cover",
        height: "100vh"
    }}
>

I would like to lazy load the backgroundImage.

I haven't yet found good components/utilities for doing this. Does anyone have any ideas?


Solution

  • Here is a simple component to lazy load images:

    class LazyBackground extends React.Component {
      state = { src: null };
    
      componentDidMount() {
        const { src } = this.props;
    
        const imageLoader = new Image();
        imageLoader.src = src;
    
        imageLoader.onload = () => {
          this.setState({ src });
        };
      }
    
      render() {
        return <div {...this.props} style={{ backgroundImage: `url(${this.state.src || this.props.placeholder})` }} />;
      }
    }
    

    You would call it with <LazyBackground src='path/to/hd.jpg' placeholder='path/to/placeholder.jpg' />