In React Native, Dimensions and PixelRatio help you build responsive UIs that adapt correctly to different screen sizes, resolutions, and device densities.
Dimensions gives physical screen size, while PixelRatio converts layout size to device pixels.
// 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();
// 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>
);
}
The box dynamically adjusts to half of the device width. Border thickness stays visually consistent across devices due to PixelRatio rounding.
Use the controls below to simulate how Dimensions and PixelRatio affect calculations.
// 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
Dimensions.addEventListener for orientation changes