Last active
January 11, 2016 15:21
-
-
Save AWaselnuk/2c9ca315feb1309aa48b to your computer and use it in GitHub Desktop.
A React Component to handle responsive product images from the Shopify API
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
import React from 'react'; | |
const SIZES = { | |
'pico': 16, | |
'icon': 32, | |
'thumb': 50, | |
'small': 100, | |
'compact': 160, | |
'medium': 240, | |
'large': 480, | |
'grande': 600, | |
'1024x1024': 1024, | |
'2048x2048': 2048, | |
'master': 2048 | |
}; | |
const SIZE_NAMES = Object.keys(SIZES); | |
const PLACEHOLDER = 'placeholder'; | |
const PLACEHOLDER_SRC = '/assets/FPO/photo.jpg'; | |
export default class ShopifyImage extends React.Component { | |
constructor (props) { | |
super(props); | |
this.srcset = this.buildSrcSet(props.src, props.size); | |
this.sizes = props.sizes || '100vw'; | |
this.src = this.addSizeToSrc(props.src, props.size); | |
} | |
buildSrcSet (src, size) { | |
if (src == PLACEHOLDER) { | |
return `${PLACEHOLDER_SRC} 600w`; | |
} | |
let sizeNamePosition = SIZE_NAMES.indexOf(size); | |
let sizeNames = SIZE_NAMES.slice(sizeNamePosition, sizeNamePosition + 4); | |
return sizeNames | |
.map((sizeName) => `${this.addSizeToSrc(src, sizeName)} ${SIZES[sizeName]}w`) | |
.join(', '); | |
} | |
addSizeToSrc (src, size) { | |
if (size == 'master') { | |
return src; | |
} | |
if (src == PLACEHOLDER) { | |
return PLACEHOLDER_SRC; | |
} | |
let filetypeRegex = /(.jpg|.jpeg|.png|.gif)/g; | |
return src.replace(filetypeRegex, `_${size}$&`); | |
} | |
render () { | |
let {src, sizes, ...otherProps} = this.props; | |
return ( | |
<img src={this.src} srcSet={this.srcset} sizes={this.sizes} {...otherProps} /> | |
); | |
} | |
} | |
ShopifyImage.propTypes = { | |
// src prop can accept the value 'placeholder' | |
// in order to render the placeholder product image | |
src: React.PropTypes.string.isRequired, | |
alt: React.PropTypes.string.isRequired, | |
size: React.PropTypes.oneOf(SIZE_NAMES).isRequired, | |
sizes: React.PropTypes.string | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment