I want to have a view whose width is responsive to its container width while keeping its aspect ratio. I don't want to hard code width or height, but keep it dynamic and responsive so that it can be reused in multiple situations as a reusable component.
I hope it works similar to the following code:
<View style={{
alignSelf: 'stretch',
aspectRatio: 1.5
}} />
It should fill its container's width and set its own height dynamically based on its width.
Is this possible in react-native with flexbox?
As Hendy Irawan commented, React Native added
aspectRatio
property toStyleSheet
.https://facebook.github.io/react-native/docs/layout-props.html#aspectratio
From the document:
Thus the following should work:
Yes, you can use the Dimensions API to get the window's width, and then set height programatically. I typically call the dimensions as soon as the app loads, before you need to know the width, and then just pass the object around as needed.
This could be a custom component to accomplish your use case.