Created
April 13, 2016 12:24
-
-
Save mikelambert/12e4496ae813f2b365567b460548360a to your computer and use it in GitHub Desktop.
Renders an Image that stays proportionally sized to its original dimensions.
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
var ProportionalImage = React.createClass({ | |
getInitialState() { | |
return { | |
style: {} | |
}; | |
}, | |
propTypes: { | |
originalWidth: React.PropTypes.number.isRequired, | |
originalHeight: React.PropTypes.number.isRequired, | |
}, | |
onLayout(e) { | |
var layout = e.nativeEvent.layout; | |
var aspectRatio = this.props.originalWidth / this.props.originalHeight; | |
var measuredHeight = layout.width / aspectRatio; | |
var currentHeight = layout.height; | |
if (measuredHeight != currentHeight) { | |
this.setState({ | |
style: { | |
height: measuredHeight | |
} | |
}); | |
} | |
}, | |
render() { | |
// We catch the onLayout in the view, find the size, then resize the child (before it is laid out?) | |
return ( | |
<View | |
onLayout={this.onLayout} | |
> | |
<Image | |
{...this.props} | |
style={[this.props.style, this.state.style]} | |
/> | |
</View> | |
); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment