← Back to Chapters

Dimensions & PixelRatio

? Dimensions & PixelRatio

? Quick Overview

In React Native, Dimensions and PixelRatio help you build responsive UIs that adapt correctly to different screen sizes, resolutions, and device densities.

? Key Concepts

  • Dimensions provides screen and window width & height
  • PixelRatio handles device pixel density
  • Used together for responsive layouts
  • Prevents UI breaking on high-DPI screens

? Syntax / Theory

Dimensions gives physical screen size, while PixelRatio converts layout size to device pixels.

? View Code Example
// Import required APIs from react-native
import { Dimensions, PixelRatio } from "react-native";

// Get screen width and height
const { width, height } = Dimensions.get("window");

// Get device pixel density
const pixelDensity = PixelRatio.get();

? Code Example(s)

? View Code Example
// Responsive box using Dimensions and PixelRatio
import React from "react";
import { View, Text, Dimensions, PixelRatio } from "react-native";

const { width } = Dimensions.get("window");
const size = width / 2;
const border = PixelRatio.roundToNearestPixel(1);

export default function App() {
  return (
    <View style={{ width: size, height: size, borderWidth: border }}>
      <Text>Responsive Box</Text>
    </View>
  );
}

? Live Output / Explanation

The box dynamically adjusts to half of the device width. Border thickness stays visually consistent across devices due to PixelRatio rounding.

? Interactive / Visual Understanding

Use the controls below to simulate how Dimensions and PixelRatio affect calculations.

Box
(Width / 2)
? View Code Example
// React Native Code Execution
const { width } = Dimensions.get("window"); // returns 300
const ratio = PixelRatio.get(); // returns 2

// Logic
const boxWidth = width / 2; // 150 layout pixels
const physicalPixels = boxWidth * ratio; // 300 px

? Use Cases

  • Building responsive layouts
  • Handling tablets and foldable devices
  • Optimizing image rendering
  • Consistent borders and spacing

? Tips & Best Practices

  • Use Dimensions.addEventListener for orientation changes
  • Avoid hard-coded pixel values
  • Use PixelRatio for borders and hairlines

? Try It Yourself

  • Create a card that adapts to screen width
  • Experiment with different PixelRatio values
  • Handle landscape vs portrait mode