I want to detect screen orientation changes using the event orientationchange
, which is supported by all major mobile browsers.
I add the event listener in componentDidMount
and set the state from inside the event callback.
However, I see that when the event first fires as a result of change from portrait to landscape the state is not updated to landscape. Then when I change the orientation from landscape back to portrait, the state says the orientation is landscape. After this each time I change the orientation the state always says the opposite of the actual orientation. I'm not sure if I should be using some lifecycle react method or my detection is not good.
I tested the code using Chrome developer tools Toggle device toolbar
.
This is my code:
import React from 'react';
class AppInfo extends React.Component {
state = {
screenOrientation: 'portrait'
}
isPortraitMode = () => {
console.log(this.state);
const { screenOrientation } = this.state;
return screenOrientation === 'portrait';
}
setScreenOrientation = () => {
if (window.matchMedia("(orientation: portrait)").matches) {
console.log('orientation: portrait');
this.setState({
screenOrientation: 'portrait'
});
}
if (window.matchMedia("(orientation: landscape)").matches) {
console.log('orientation: landscape');
this.setState({
screenOrientation: 'landscape'
});
}
}
componentDidMount() {
window.addEventListener('orientationchange', this.setScreenOrientation);
}
render() {
console.log(`orientation: from render: isPortraitMode = ${this.isPortraitMode()}`);
<div>
Hello
</div>
}
}
export default AppInfo;