Skip to content

Instantly share code, notes, and snippets.

@eric-wood
Last active May 6, 2020 18:49
Show Gist options
  • Save eric-wood/6fdf0f3a09064f68712cba66ce0c948a to your computer and use it in GitHub Desktop.
Save eric-wood/6fdf0f3a09064f68712cba66ce0c948a to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from "react"
import PropTypes from "prop-types"
import { Image } from "react-native"
import useIsMounted from "ismounted"
const AutoHeightImageComponent = ({
source,
width,
style,
onHeightChange = () => {},
...props
}) => {
const [height, setHeight] = useState(0)
const isMounted = useIsMounted()
useEffect(() => {
if (source.uri) {
Image.getSize(source.uri, (w, h) => {
if (!isMounted.current) {
return
}
const newHeight = (width * h) / w
setHeight(newHeight)
onHeightChange(newHeight)
})
}
}, [props.source])
style = style || {}
style = {
...style,
width: width,
height,
}
return <Image source={source} style={style} {...props} />
}
AutoHeightImageComponent.propTypes = {
source: PropTypes.oneOfType([
PropTypes.shape({
uri: PropTypes.string,
}),
PropTypes.number,
]).isRequired,
width: PropTypes.number.isRequired,
style: PropTypes.object,
onHeightChange: PropTypes.func,
}
export default AutoHeightImageComponent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment