How to useuseWindowDimensions in React Native
In this approach, we’ll use the useWindowDimensions hook to effortlessly access the width and height of the screen.
Example: The code defines a React Native component named ‘App’ that showcases the dimensions of the device screen. It import necessary components from ‘react-native’ while utilizing the useWindowDimensions hook to obtain both the width and height of the screen.
Javascript
// App.js file import React from "react" ; import { View, Text, useWindowDimensions, StyleSheet, } from "react-native" ; const App = () => { const { width, height } = useWindowDimensions(); return ( <View style={styles.container}> <Text style={styles.text}>w3wiki</Text> <View style={styles.dimensionContainer}> <Text style={styles.dimensionText}> Screen Width: {width} </Text> <Text style={styles.dimensionText}> Screen Height: {height} </Text> </View> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center" , alignItems: "center" , backgroundColor: "#f0f0f0" , }, text: { fontSize: 30, fontWeight: "bold" , marginBottom: 20, color: "green" , }, dimensionContainer: { backgroundColor: "white" , borderRadius: 10, padding: 20, shadowColor: "#000" , shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.25, shadowRadius: 3.84, elevation: 5, }, dimensionText: { fontSize: 18, marginBottom: 10, color: "#666" , }, }); export default App; |
Output:
How to Get Window Width and Height In React Native ?
In this article, we’ll explore two different approaches to obtaining the screen width and height in a React Native application.
Screen dimensions, including width and height, play a vital role in designing user interfaces that adapt seamlessly to different devices and orientations. By understanding these dimensions, developers empower themselves to create responsive layouts and deliver a cohesive user experience across diverse devices.