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?
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})` }} />
)
}
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' />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With