Last active
September 10, 2020 21:53
-
-
Save sandren/c85099d387362b33daf33b7f3c8aed81 to your computer and use it in GitHub Desktop.
responsive-image.js: A simple wrapper around the gatsby-image component to make setting the object fit and object position properties easier.
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'; | |
import GatsbyImage from 'gatsby-image'; | |
import PropTypes from 'prop-types'; | |
const Image = ({ objectFit, objectPosition, ...rest }) => { | |
let wrapperStyles = {}; | |
let imageStyles = {}; | |
if (objectFit === 'contain') { | |
wrapperStyles.width = '100%'; | |
wrapperStyles.maxWidth = '100%'; | |
} | |
switch (objectFit) { | |
case 'contain': | |
imageStyles.objectFit = 'contain'; | |
break; | |
case 'cover': | |
imageStyles.objectFit = 'cover'; | |
break; | |
case 'fill': | |
imageStyles.objectFit = 'fill'; | |
break; | |
case 'none': | |
imageStyles.objectFit = 'none'; | |
break; | |
case 'scale-down': | |
imageStyles.objectFit = 'scale-down'; | |
break; | |
default: | |
break; | |
} | |
switch (objectPosition) { | |
case 'center': | |
imageStyles.objectPosition = 'center center'; | |
break; | |
case 'left': | |
imageStyles.objectPosition = 'left center'; | |
break; | |
case 'left top': | |
imageStyles.objectPosition = 'left top'; | |
break; | |
case 'top': | |
imageStyles.objectPosition = 'center top'; | |
break; | |
case 'right top': | |
imageStyles.objectPosition = 'right top'; | |
break; | |
case 'right': | |
imageStyles.objectPosition = 'right center'; | |
break; | |
case 'right bottom': | |
imageStyles.objectPosition = 'right bottom'; | |
break; | |
case 'bottom': | |
imageStyles.objectPosition = 'center bottom'; | |
break; | |
case 'left bottom': | |
imageStyles.objectPosition = 'left bottom'; | |
break; | |
default: | |
break; | |
} | |
return ( | |
<GatsbyImage | |
style={wrapperStyles} | |
imgStyle={imageStyles} | |
placeholderStyle={imageStyles} | |
{...rest} | |
/> | |
); | |
}; | |
Image.defaultProps = { | |
objectFit: 'cover', | |
objectPosition: 'center', | |
}; | |
Image.propTypes = { | |
objectFit: PropTypes.string, | |
objectPosition: PropTypes.string, | |
}; | |
export default Image; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment