Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically set height of view based on its width by keeping aspect ratio?

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?

like image 544
Joon Avatar asked May 10 '16 09:05

Joon


2 Answers

As Hendy Irawan commented, React Native added aspectRatio property to StyleSheet.

https://facebook.github.io/react-native/docs/layout-props.html#aspectratio

From the document:

aspectRatio?: number

Aspect ratio control the size of the undefined dimension of a node. Aspect ratio is a non-standard property only available in react native and not CSS.

On a node with a set width/height aspect ratio control the size of the unset dimension On a node with a set flex basis aspect ratio controls the size of the node in the cross axis if unset On a node with a measure function aspect ratio works as though the measure function measures the flex basis On a node with flex grow/shrink aspect ratio controls the size of the node in the cross axis if unset Aspect ratio takes min/max dimensions into account

Thus the following should work:

const styles = StyleSheet.create({
  view: {
    aspectRatio: 1.5,
  }
});

// later in render()
<View style={styles.view} />
like image 92
Joon Avatar answered Oct 08 '22 16:10

Joon


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.

import {Dimensions} from 'react-native'

...

const AspectView = ({style, aspectRatio, children, ...props}) => {
  let {height, width} = Dimensions.get('window');
  return (
    <View style={[style, {height: width * aspectRatio}] {...props}>{children}</View>
  )
}
like image 38
BradByte Avatar answered Oct 08 '22 15:10

BradByte