I have created a Section component which will take in an image as a property and its children as content to be displayed within the section, so the component would look as follows...
<Section image={'path/to/image'}>
//content
</Section>
The component will take the image property and set it as a url for background-image style...
let sectionStyle = {
backgroundImage: `url(${this.props.image})`
}
which will then be processed in the return element...
return (
<section
style={this.props.image ? sectionStyle : null}>
<div>
{this.props.children}
</div>
</section>
)
My question is, is it possible to Lazyload the background image whilst also not compromising the contents availability for SEO? in other words i want to avoid LazyLoading the entire Section, but somehow LazyLoad just the image associated with the Section.
An updated version of @naoise-golden 's answer
import PropTypes from 'prop-types';
import React from 'react';
export default class LazyImage extends React.Component {
constructor (props) {
super(props);
this.state = {
src: null,
};
}
componentDidMount () {
const { src } = this.props;
console.log('LazyImage componentDidMount props:', this.props);
const imageLoader = new Image();
imageLoader.src = src;
imageLoader.onload = () => {
console.log('LazyImage loaded src:', src);
this.setState({ src });
};
}
render () {
const { placeholder, className, height, width, alt } = this.props;
const { src } = this.state;
return (
<img src={src || placeholder} className={className} height={height} width={width} alt={alt} />
);
}
}
LazyImage.propTypes = {
src: PropTypes.string,
placeholder: PropTypes.string,
className: PropTypes.string,
height: PropTypes.number,
width: PropTypes.number,
alt: PropTypes.string,
};
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