React Native Fun

Little Atoms of React Native. Tips, Tricks, and How Tos.

Making a square component (or any other fixed ratio)

React Native has built in support for styling components with a fixed ratio. Using this is especially useful if you want to have a component such as an image in a grid or a list which is always the same shape.

The aspect ratio of a component is controlled using the aspectRatio style property. This is a basic layout styling property and is available for all views.

Setting the aspect ratio to 1 cause the view to be square. This is because the ratio is defined by the width : height. 1 : 1 means the width and height are the same, so the view is square.

import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { Constants } from 'expo';

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.fixedRatio} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white'
  },
  fixedRatio: {
    backgroundColor: 'rebeccapurple',
    flex: 1,
    aspectRatio: 1
  },
});

Screenshot showing a square React Native view

For other aspect ratios, you can write them as width / height. For example, if you want a view which is 16:9 (the standard TV widescreen ratio) you can set this property:

aspectRation: 16 / 9

Screenshot showing a 16/9 React Native view

As mentioned, this is especially useful if you want to ensure all rows in a ListView are the same aspect ratio.