Forked from vincentriemer/react-image-objectfit-fallback.js
Created
December 24, 2017 09:02
-
-
Save arekbartnik/247680c762657a3622a6ed59dd793c3f to your computer and use it in GitHub Desktop.
Image React Component with `object-fit` Fallback
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
// @flow | |
import * as React from "react"; | |
import getStyleProp from "desandro-get-style-property"; | |
const supportsObjectFit = !!getStyleProp("objectFit"); | |
type Props = React.ElementProps<"img">; | |
export default class Image extends React.Component<Props> { | |
renderFallback = () => { | |
const { style, src, ...restProps } = this.props; | |
return ( | |
<div | |
style={{ | |
...style, | |
backgroundImage: `url(${src})`, | |
backgroundSize: style.objectFit, | |
backgroundPosition: "center center", | |
position: "relative", | |
}} | |
> | |
<img | |
style={{ | |
display: "block", | |
position: "absolute", | |
top: 0, | |
left: 0, | |
width: "100%", | |
height: "100%", | |
opacity: 0, | |
}} | |
src={src} | |
{...restProps} | |
/> | |
</div> | |
); | |
}; | |
renderNative = () => { | |
const { style, ...restProps } = this.props; | |
return ( | |
<img | |
style={{ | |
...style, | |
display: "block", | |
}} | |
{...restProps} | |
/> | |
); | |
}; | |
render() { | |
const isUsingObjectFit = !!this.props.style.objectFit; | |
return isUsingObjectFit && supportsObjectFit | |
? this.renderNative() | |
: this.renderFallback(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment