Last active
June 29, 2018 05:57
-
-
Save glemiere/079e9c7aad4c04e6b90c1fc150c7479f to your computer and use it in GitHub Desktop.
Simple react component to produce an isomorphic iDangerous Swiper slide with lazy-loading and SVG SQIP preview.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/********** | |
Slide.jsx | |
--------------- | |
Simple react component to produce an isomorphic iDangerous Swiper slide with lazy-loading and SVG SQIP preview. | |
--------------- | |
Requires iDangerous Swiper and sqip-loader : | |
https://idangero.us/ | |
https://www.npmjs.com/package/sqip-loader | |
**********/ | |
//Component styling | |
import style from './style.scss' | |
// See : https://github.com/glemiere/nextjs-starter/blob/master/helpers/index.js | |
import helpers from '../../../helpers'; | |
class Slide extends React.Component { | |
constructor(props){ | |
super(props); | |
this.state = { | |
imageLoaded:false, | |
selectorName: 'slide-' + this.props.id, | |
src:this.props.slide, | |
placeholder:this.props.slide | |
}; | |
} | |
// Update component state when image is loaded. | |
setImageLoaded = () => { | |
this.setState({imageLoaded:true}); | |
} | |
// Enable SVG preview in production | |
componentWillMount = () => { | |
if (process.env.NODE_ENV == 'production') { | |
this.setState({ | |
src:this.props.slide.src, | |
placeholder:this.props.slide.preview | |
}); | |
} | |
} | |
// Set SVG preview as div background to avoid white area behind responsive picture | |
componentDidMount = () => { | |
const background = 'background: url("'+this.state.placeholder+'") no-repeat center center;'; | |
const backgroundSize = 'background-size: cover;'; | |
const style = background + backgroundSize; | |
//Creates CSS rule when app run on client. | |
if (!helpers.isServer) | |
helpers.createCSSSelector('.' + this.state.selectorName, style); | |
} | |
// Renders the slide with it's preview and HD pictures | |
render() { | |
return ( | |
<div className={`swiper-slide ${this.state.selectorName}`}> | |
{/* Image preview */} | |
<img | |
data-src={this.state.placeholder} | |
className={`swiper-lazy image-preview ${`loaded-` + this.state.imageLoaded} ${this.state.selectorName}`} | |
alt={`blurred picture`} | |
/> | |
{/* Image HD */} | |
<img | |
data-src={this.state.src} | |
className={`swiper-lazy image-hd ${`loaded-` + this.state.imageLoaded}`} | |
onLoad={this.setImageLoaded} | |
alt={`picture`} | |
/> | |
<style dangerouslySetInnerHTML={{ __html: style }} /> | |
</div> | |
); | |
} | |
} | |
export default Slide |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment