Expo Web
Search…
Aspect Ratio
Universal solution to the missing aspect ratio prop
Because the aspectRatio style prop isn't available in react-native-web's StyleSheet API, we need to improvise a bit. Here is a View which accepts an aspectRatio style prop and calculates the ratio for you!

Example Snack

1
import * as React from 'react';
2
import { Text, View, StyleSheet } from 'react-native';
3
4
function AspectView(props) {
5
const [layout, setLayout] = React.useState(null);
6
7
const { aspectRatio = 1, ...inputStyle } =
8
StyleSheet.flatten(props.style) || {};
9
const style = [inputStyle, { aspectRatio }];
10
11
if (layout) {
12
const { width = 0, height = 0 } = layout;
13
if (width === 0) {
14
style.push({ width: height * aspectRatio, height });
15
} else {
16
style.push({ width, height: width * aspectRatio });
17
}
18
}
19
20
return (
21
<View
22
{...props}
23
style={style}
24
onLayout={({ nativeEvent: { layout } }) => setLayout(layout)}
25
/>
26
);
27
}
28
29
// ...
30
31
return <AspectView style={{ width: 48, aspectRatio: 0.75 }} />;
Copied!
Copy link