Skip to content

Instantly share code, notes, and snippets.

@markhowellsmead
Last active July 9, 2019 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markhowellsmead/55a6eb51d645d2164e8f2212e6d3866c to your computer and use it in GitHub Desktop.
Save markhowellsmead/55a6eb51d645d2164e8f2212e6d3866c to your computer and use it in GitHub Desktop.
BackgroundImageElement for Gutenberg Block use
/**
* BackgroundImageElement
* Outputs a figure and image for use as a background image (using object-fit
* in CSS - not provided). The HTML output contains the aria attribute
* 'aria-hidden' as background images are purely decorative.
* This version includes LazySizes CSS classes and a NOSCRIPT tag for use
* in projects by sayhello.ch.
*
* { backgroundImage } is a WordPress Image Object
*
* mhm 9.7.2019
*
* Usage:
*
* import { BackgroundImageElement } from './BackgroundImageElement.jsx';
* …
* <BackgroundImageElement
* image={backgroundImage}
* className={className}
/>
*/
const {Component} = wp.element;
export class BackgroundImageElement extends Component {
constructor(props) {
super(...arguments);
this.props = props;
}
render() {
var {
image,
className,
context
} = this.props;
if (!image || !image.url || !image.sizes) {
return '';
}
if (!className) {
className = 'generic';
}
let srcset = [], alreadyGotSize = [];
Object.keys(image.sizes).map(size => {
if(alreadyGotSize.indexOf(image.sizes[size].width) < 0){
srcset.push(image.sizes[size].url + ' ' + image.sizes[size].width + 'w');
alreadyGotSize.push(image.sizes[size].width);
}
});
srcset = srcset.join(',');
if(context == 'edit') {
return (<figure className={className + '__figure'}>
<img
alt={image.alt}
className={className + '__image'}
src={image.url}
srcset={srcset}/>
</figure>);
}else{
return (<figure className={className + '__figure o-lazyimage'}>
<img
alt={image.alt}
className={className + '__image o-lazyimage__image o-lazyimage__image--lazyload'}
data-sizes="auto"
src={image.url}
data-srcset={srcset}/>
<noscript>
<img src={image.url} srcset={srcset} />
</noscript>
</figure>);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment