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
import { Dimensions } from 'react-native';
const windowWidth = Dimensions.get('window').width;
const 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.
import React, { Component } from "react";
import { View, StyleSheet, Text, Dimensions } from "react-native";
const window = Dimensions.get("window");
const screen = Dimensions.get("screen");
class App extends Component {
state = {
dimensions: {
window,
screen
}
};
onChange = ({ window, screen }) => {
this.setState({ dimensions: { window, screen } });
};
componentDidMount() {
Dimensions.addEventListener("change", this.onChange);
}
componentWillUnmount() {
Dimensions.removeEventListener("change", this.onChange);
}
render() {
const { dimensions } = this.state;
return (
<View style={styles.container}>
<Text>{`Window Dimensions: height - ${dimensions.window.height}, width - ${dimensions.window.width}`}</Text>
<Text>{`Screen Dimensions: height - ${dimensions.screen.height}, width - ${dimensions.screen.width}`}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center"
}
});
export default App;
Thanks for reading…