Hello Friends,
Welcome To Infinitbility!
This article will help you to get screen width and height in react native, in react native for responsiveness we need many times screen with and heght.
Let’s start today’s article React Native Dimensions Example
React Native provide Dimensions component to get and manage screen width and height.
React Native Dimensions Example article will clear your below topics.
- How to get screen width and height in react native
- How to get updated width and height when device rotate in react native or other cases.
How to get screen width and height in react native
React Native Dimensions will provide both height and width of screen and also window, then what’s diffrance between window and screen in react native dimensions?
window
- Size of the visible Application windowscreen
- Size of the device’s screen
You wil get screen width and height like below example
1import { Dimensions } from 'react-native';234const windowWidth = Dimensions.get('window').width;5const windowHeight = Dimensions.get('window').height;
How to get updated width and height when device rotate in react native or other cases ( foldable devices ).
If you are targeting foldable devices or devices which can change the screen size or app window size, you can use the event listener available in the Dimensions module as shown in the below example.
React Native Dimensions EventListener
will update width and height value if it change. you will try like below.
1import React, { Component } from "react";2import { View, StyleSheet, Text, Dimensions } from "react-native";34const window = Dimensions.get("window");5const screen = Dimensions.get("screen");67class App extends Component {8 state = {9 dimensions: {10 window,11 screen12 }13 };1415 onChange = ({ window, screen }) => {16 this.setState({ dimensions: { window, screen } });17 };1819 componentDidMount() {20 Dimensions.addEventListener("change", this.onChange);21 }2223 componentWillUnmount() {24 Dimensions.removeEventListener("change", this.onChange);25 }2627 render() {28 const { dimensions } = this.state;2930 return (31 <View style={styles.container}>32 <Text>{`Window Dimensions: height - ${dimensions.window.height}, width - ${dimensions.window.width}`}</Text>33 <Text>{`Screen Dimensions: height - ${dimensions.screen.height}, width - ${dimensions.screen.width}`}</Text>34 </View>35 );36 }37}3839const styles = StyleSheet.create({40 container: {41 flex: 1,42 justifyContent: "center",43 alignItems: "center"44 }45});4647export default App;
Thanks for reading…
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.