2020-08-17 21:07:16 +01:00
|
|
|
import React from 'react'
|
2020-08-17 21:59:29 +01:00
|
|
|
import PropTypes from 'prop-types'
|
2020-08-19 01:39:06 +01:00
|
|
|
import { CX } from '../constants'
|
2020-02-19 23:57:07 +00:00
|
|
|
|
2020-08-18 01:57:35 +01:00
|
|
|
class Image extends React.PureComponent {
|
2020-02-19 23:57:07 +00:00
|
|
|
|
2020-04-04 00:18:26 +01:00
|
|
|
state = {
|
|
|
|
error: false,
|
|
|
|
}
|
|
|
|
|
|
|
|
handleOnError = () => {
|
|
|
|
this.setState({ error: true })
|
|
|
|
}
|
|
|
|
|
2020-02-19 23:57:07 +00:00
|
|
|
render() {
|
2020-04-08 02:06:59 +01:00
|
|
|
const {
|
2020-04-24 04:17:27 +01:00
|
|
|
alt,
|
2020-04-08 02:06:59 +01:00
|
|
|
src,
|
|
|
|
fit,
|
|
|
|
className,
|
|
|
|
nullable,
|
2020-08-17 22:28:04 +01:00
|
|
|
isLazy,
|
2020-05-01 06:50:27 +01:00
|
|
|
imageRef,
|
2020-04-08 02:06:59 +01:00
|
|
|
...otherProps
|
|
|
|
} = this.props
|
2020-04-04 00:18:26 +01:00
|
|
|
const { error } = this.state
|
2020-02-19 23:57:07 +00:00
|
|
|
|
2020-08-19 01:39:06 +01:00
|
|
|
const classes = CX(className, {
|
2020-08-18 21:49:11 +01:00
|
|
|
d: 1,
|
2020-04-08 02:06:59 +01:00
|
|
|
objectFitCover: !!src && fit === 'cover',
|
2020-06-07 20:57:29 +01:00
|
|
|
bgSecondary: !src,
|
2020-02-19 23:57:07 +00:00
|
|
|
})
|
|
|
|
|
2020-04-04 00:18:26 +01:00
|
|
|
//If error and not our own image
|
|
|
|
if (error && nullable) {
|
|
|
|
return null
|
|
|
|
}
|
2020-04-08 02:06:59 +01:00
|
|
|
|
|
|
|
if (!src) {
|
|
|
|
return (
|
|
|
|
<div className={classes} />
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2020-02-19 23:57:07 +00:00
|
|
|
return (
|
|
|
|
<img
|
2020-04-24 04:17:27 +01:00
|
|
|
alt={alt}
|
2020-02-19 23:57:07 +00:00
|
|
|
className={classes}
|
|
|
|
{...otherProps}
|
2020-05-01 06:50:27 +01:00
|
|
|
ref={imageRef}
|
2020-04-08 02:06:59 +01:00
|
|
|
src={src}
|
2020-04-04 00:18:26 +01:00
|
|
|
onError={this.handleOnError}
|
2020-08-17 22:28:04 +01:00
|
|
|
loading={isLazy ? 'lazy' : undefined}
|
2020-02-19 23:57:07 +00:00
|
|
|
/>
|
|
|
|
)
|
|
|
|
}
|
2020-04-08 02:06:59 +01:00
|
|
|
|
2020-08-18 01:57:35 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
Image.propTypes = {
|
|
|
|
alt: PropTypes.string.isRequired,
|
|
|
|
isLazy: PropTypes.string,
|
|
|
|
className: PropTypes.string,
|
|
|
|
width: PropTypes.oneOfType([
|
|
|
|
PropTypes.string,
|
|
|
|
PropTypes.number,
|
|
|
|
]),
|
|
|
|
height: PropTypes.oneOfType([
|
|
|
|
PropTypes.string,
|
|
|
|
PropTypes.number,
|
|
|
|
]),
|
|
|
|
fit: PropTypes.oneOf(['contain', 'cover', 'tile', 'none']),
|
|
|
|
nullable: PropTypes.bool,
|
|
|
|
lazy: PropTypes.bool,
|
|
|
|
imageRef: PropTypes.func,
|
|
|
|
}
|
|
|
|
|
|
|
|
Image.defaultProps = {
|
|
|
|
width: '100%',
|
|
|
|
fit: 'cover',
|
|
|
|
}
|
|
|
|
|
|
|
|
export default Image
|