9 February 2020

Detect device portrait or landscape example in react native

  • Create Components folder under src folder
  • Add DetectDevicePortraitLandscape.js file and add below Code
import React, { Component } from "react";
import { StyleSheetViewText } from "react-native";

export default class DetectDevicePortraitLandscape extends Component {
  constructor() {
    super();
    this.state = {
      OrientationStatus: "",
      Height_Layout: "",
      Width_Layout: ""
    };
  }
  componentDidMount() {
    this.DetectOrientation();
  }
  DetectOrientation() {
    if (this.state.Width_Layout > this.state.Height_Layout) {
      this.setState({
        OrientationStatus: "Landscape Mode"
      });
    } else {
      this.setState({
        OrientationStatus: "Portrait Mode"
      });
    }
  }
  render() {
    return (
      <View
        style={styles.MainContainer}
        onLayout={event =>
          this.setState(
            {
              Width_Layout: event.nativeEvent.layout.width,
              Height_Layout: event.nativeEvent.layout.height
            },
            () => this.DetectOrientation()
          )
        }
      >
        <Text style={styles.TextStyle}> {this.state.OrientationStatus} </Text>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  MainContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    margin: 10
  },
  TextStyle: {
    fontSize: 20,
    color: "#000"
  }
});
  • Open App.js file and update code as below
import React from 'react';
import {  Text,View,StyleSheet } from 'react-native';
import DetectDevicePortraitLandscape from './src/Component/DetectDevicePortraitLandscape'

 const  App=()=> {
  return (
    <View style={styles.container}>
      <DetectDevicePortraitLandscape/>
    </View>
  );
}
export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    paddingTop:80
  },
});


Output:

No comments:

Post a Comment