Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 973
Vivian Avatar asked Jul 31 '18 06:07

Vivian


2 Answers

Here's a custom React hook based on Naoise's answer:

const useProgressiveImage = src => {  
  const [sourceLoaded, setSourceLoaded] = useState(null)

  useEffect(() => {
    const img = new Image()
    img.src = src
    img.onload = () => setSourceLoaded(src)
  }, [src])

  return sourceLoaded 
}

Usage:

const Component = (source, placeholder) => {
  const loaded = useProgressiveImage(source)

  return (
    <div style={{ backgroundImage: `url(${loaded || placeholder})` }} />
  )
}
like image 65
Jesper N Avatar answered Nov 17 '22 17:11

Jesper N


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' />

like image 38
Naoise Golden Avatar answered Nov 17 '22 17:11

Naoise Golden