|
| 1 | +import Img from 'next/image'; |
| 2 | + |
| 3 | +import PropTypes from 'prop-types'; |
| 4 | +import cx from 'classnames'; |
| 5 | +import {DEFAULT_IMG_URL} from '../../utils/constants/images'; |
| 6 | + |
| 7 | +/** |
| 8 | + * Image Component. |
| 9 | + * We don't need to add srcSet, as Next js will generate that. |
| 10 | + * @see https://nextjs.org/docs/api-reference/next/image#other-props |
| 11 | + * @see https://nextjs.org/docs/basic-features/image-optimization#device-sizes |
| 12 | + * |
| 13 | + * @param {Object} props Component props. |
| 14 | + * |
| 15 | + * @return {jsx} |
| 16 | + */ |
| 17 | +const Image = ( props ) => { |
| 18 | +const {altText, title, width, height, sourceUrl, className, layout, objectFit, containerClassNames, showDefault, ...rest} = props; |
| 19 | + |
| 20 | +if ( ! sourceUrl && ! showDefault ) { |
| 21 | +return null; |
| 22 | +} |
| 23 | + |
| 24 | +/** |
| 25 | + * If we use layout = fill then, width and height of the image cannot be used. |
| 26 | + * and the image fills on the entire width and the height of its parent container. |
| 27 | + * That's we need to wrap our image in a container and give it a height and width. |
| 28 | + * Notice that in this case, the given height and width is being used for container and not img. |
| 29 | + */ |
| 30 | +if ( 'fill' === layout ) { |
| 31 | +const attributes = { |
| 32 | +alt: altText || title, |
| 33 | +src: sourceUrl || ( showDefault ? DEFAULT_IMG_URL : '' ), |
| 34 | +layout: 'fill', |
| 35 | +className: cx( 'object-cover', className ), |
| 36 | +...rest |
| 37 | +}; |
| 38 | + |
| 39 | +return ( |
| 40 | +<div className={cx( 'relative', containerClassNames ) }> |
| 41 | +<Img {...attributes}/> |
| 42 | +</div> |
| 43 | +); |
| 44 | +} else { |
| 45 | +const attributes = { |
| 46 | +alt: altText || title, |
| 47 | +src: sourceUrl || ( showDefault ? DEFAULT_IMG_URL : '' ), |
| 48 | +width: width || 'auto', |
| 49 | +height: height || 'auto', |
| 50 | +className, |
| 51 | +...rest |
| 52 | +}; |
| 53 | +return <Img {...attributes} />; |
| 54 | +} |
| 55 | +}; |
| 56 | + |
| 57 | +Image.propTypes = { |
| 58 | +altText: PropTypes.string, |
| 59 | +title: PropTypes.string, |
| 60 | +sourceUrl: PropTypes.string, |
| 61 | +layout: PropTypes.string, |
| 62 | +showDefault: PropTypes.bool, |
| 63 | +containerClassName: PropTypes.string, |
| 64 | +className: PropTypes.string |
| 65 | +}; |
| 66 | + |
| 67 | +Image.defaultProps = { |
| 68 | +altText: '', |
| 69 | +title: '', |
| 70 | +sourceUrl: '', |
| 71 | +showDefault: true, |
| 72 | +containerClassNames: '', |
| 73 | +className: 'product__image', |
| 74 | +}; |
| 75 | + |
| 76 | +export default Image; |
0 commit comments