Last active
November 15, 2021 17:36
-
-
Save vincentriemer/251900608569b1ff71b918b1f6ca95bc to your computer and use it in GitHub Desktop.
Image React Component with `object-fit` Fallback
This file contains 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