0
0
React Nativemobile~5 mins

Responsive dimensions (Dimensions API) in React Native

Choose your learning style9 modes available
Introduction

Responsive dimensions help your app look good on all screen sizes. They let you get the device's width and height to adjust layouts easily.

You want a button to be half the screen width on any device.
You need to adjust font size based on screen height.
You want images to scale nicely on phones and tablets.
You want to create layouts that adapt to portrait and landscape modes.
Syntax
React Native
import { Dimensions } from 'react-native';

const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;

Dimensions.get('window') returns the width and height of the app's usable screen area.

You can also use Dimensions.get('screen') to get the entire screen size including status bars.

Examples
Get the current width and height of the app window.
React Native
const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;
Get the full screen size including areas like status bar.
React Native
const screenWidth = Dimensions.get('screen').width;
const screenHeight = Dimensions.get('screen').height;
Calculate half of the screen width for responsive layout.
React Native
const halfWidth = Dimensions.get('window').width / 2;
Sample App

This app shows a blue box sized to 80% of the screen width and 30% of the screen height. The box's size changes if you rotate the device or use a different screen size.

React Native
import React from 'react';
import { View, Text, StyleSheet, Dimensions } from 'react-native';

export default function App() {
  const windowWidth = Dimensions.get('window').width;
  const windowHeight = Dimensions.get('window').height;

  return (
    <View style={styles.container}>
      <View style={[styles.box, { width: windowWidth * 0.8, height: windowHeight * 0.3 }]}>
        <Text style={styles.text}>Responsive Box</Text>
        <Text style={styles.text}>Width: {Math.round(windowWidth * 0.8)} px</Text>
        <Text style={styles.text}>Height: {Math.round(windowHeight * 0.3)} px</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f0f0f0'
  },
  box: {
    backgroundColor: '#4a90e2',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 10
  },
  text: {
    color: 'white',
    fontSize: 18,
    marginVertical: 2
  }
});
OutputSuccess
Important Notes

Dimensions values do not update automatically on screen rotation. Use the useWindowDimensions hook for auto-updating dimensions.

Use percentages of screen size for flexible layouts instead of fixed pixel values.

Summary

Use Dimensions.get('window') to get screen width and height.

Calculate sizes as fractions of screen dimensions for responsive design.

For dynamic updates on rotation, consider useWindowDimensions hook.