react-native-responsive-screen
react-native-responsive-screen copied to clipboard
Orientation Changes on imported/external StyleSheet.Create objects
I currently have an app that uses External JS/style files that exports different StyleSheet.create() objects, which will be reused across the app. In your example of detecting orientation changes, you have put StyleSheet.create() inside the render, so it can be modified on every orientation change. However your example seems difficult to apply in my existing app code base, because I can't export objects from inside the render method. Do you have any solution for this?
Once you called listenOrientationChange
you'll have orientation
in the component's state you can use this to detect which style will be applied.
Example 1
import React, { Component } from 'react';
import { StyleSheet, View, Text } from 'react-native';
import {
listenOrientationChange,
removeOrientationListener
} from 'react-native-responsive-screen';
class AwesomeComponent extends Component {
componentDidMount() {
listenOrientationChange(this);
}
componentWillUnmount() {
removeOrientationListener();
}
render() {
return (
<View style={styles.container(this.state.orientation)}/>
);
}
}
const styles = StyleSheet.create({
container: orientation => ({
flex: 1,
backgroundColor: orientation === 'portrait' ? 'blue' : 'red'
})
});
export default AwesomeComponent;
Example 2
import React, { Component } from 'react';
import { StyleSheet, View, Text } from 'react-native';
import {
listenOrientationChange,
removeOrientationListener
} from 'react-native-responsive-screen';
class AwesomeComponent extends Component {
componentDidMount() {
listenOrientationChange(this);
}
componentWillUnmount() {
removeOrientationListener();
}
render() {
return (
<View style={
this.state.orientation === 'portrait'
? portraitStyles.container
: landscapeStyles.container
}/>
);
}
}
// Seperated style objects
const portraitStyles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'blue'
}
});
const landscapeStyles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'red'
}
});
export default AwesomeComponent;