Skip to content

Instantly share code, notes, and snippets.

@mikelambert
Created April 13, 2016 12:24
Show Gist options
  • Save mikelambert/12e4496ae813f2b365567b460548360a to your computer and use it in GitHub Desktop.
Save mikelambert/12e4496ae813f2b365567b460548360a to your computer and use it in GitHub Desktop.
Renders an Image that stays proportionally sized to its original dimensions.
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