gab-social/app/javascript/gabsocial/components/image.js

85 lines
1.5 KiB
JavaScript
Raw Normal View History

import React from 'react'
import PropTypes from 'prop-types'
2020-02-19 23:57:07 +00:00
import classNames from 'classnames/bind'
const cx = classNames.bind(_s)
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,
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
const classes = cx(className, {
d: 1,
2020-04-08 02:06:59 +01:00
objectFitCover: !!src && fit === 'cover',
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}
loading={isLazy ? 'lazy' : undefined}
2020-02-19 23:57:07 +00:00
/>
)
}
2020-04-08 02:06:59 +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