I am writing a Universal iPhone/iPad application using React-Native. However I am struggling to render my view correctly when the orientation changes. Following is the source code for js file:
'use strict';
var React = require('react-native');
var {
Text,
View
} = React;
var CardView = require('./CardView');
var styles = React.StyleSheet.create({
container:{
flex:1,
backgroundColor: 'red'
}
});
class MySimpleApp extends React.Component {
render() {
return <View style={styles.container}/>;
}
}
React.AppRegistry.registerComponent('SimpleApp', () => MySimpleApp);
This is how it renders in Portrait (which is correct):
However when the device is rotated. The red view does not rotate accordingly.
The simplest way is:
import React, { Component } from 'react';
import { Dimensions, View, Text } from 'react-native';
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
}
this.onLayout = this.onLayout.bind(this);
}
onLayout(e) {
this.setState({
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
});
}
render() {
return(
<View
onLayout={this.onLayout}
style={{width: this.state.width}}
>
<Text>Layout width: {this.state.width}</Text>
</View>
);
}
}
It pretty simple to respond orientation change in react native. Every view in react native have a listener called onLayout which get invoked upon orientation change. We just need to implement this. It's better to store dimension in state variable and update on each orientation change so that re-rendering happens after change. Other wise we need to reload the view to respond the orientation change.
import React, { Component } from "react";
import { StyleSheet, Text, View, Image, Dimensions } from "react-native";
var { height, width } = Dimensions.get("window");
export default class Com extends Component {
constructor() {
console.log("constructor");
super();
this.state = {
layout: {
height: height,
width: width
}
};
}
_onLayout = event => {
console.log(
"------------------------------------------------" +
JSON.stringify(event.nativeEvent.layout)
);
this.setState({
layout: {
height: event.nativeEvent.layout.height,
width: event.nativeEvent.layout.width
}
});
};
render() {
console.log(JSON.stringify(this.props));
return (
<View
style={{ backgroundColor: "red", flex: 1 }}
onLayout={this._onLayout}
>
<View
style={{
backgroundColor: "green",
height: this.state.layout.height - 10,
width: this.state.layout.width - 10,
margin: 5
}}
/>
</View>
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With