Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling the screen orientation change in ReactJS

Tags:

reactjs

I am trying to create a Component whose content changes when the screen orientation(portrait/landscape) changes. This is what I am doing:

 var Greeting = React.createClass({
    getInitialState: function() {
        return {orientation: true}
    },
    handleChange: function() {
        if ('onorientationchange' in window) {
            window.addEventListener("orientationchange", function() {
                this.setState({
                    orientation: !this.state.orientation
                })
                console.log("onorientationchange");
            }, false);
        } else if ('onresize' in window) {
            window.addEventListener("resize", function() {
                this.setState({
                    orientation: !this.state.orientation
                })
                console.log("resize");
            }, false);
        }
    },
    render: function() {
        var message = this.state.orientation ? "Hello" : "Good bye"
        return <p>{message}</p>;
    }
});

ReactDOM.render(
    <Greeting/>, document.getElementById('container'));

How to make sure the state is mutated when the orientation change event is fired .

like image 487
Diablo3093 Avatar asked Sep 07 '16 12:09

Diablo3093


People also ask

How do you handle screen orientation changes in react native?

Screen orientation lock​ For Android, open the AndroidManifest. xml file and within the activity element add 'android:screenOrientation="portrait"' to lock to portrait or 'android:screenOrientation="landscape"' to lock to landscape.

Which method is used to screen orientation?

In AndroidManifest. xml file add the screenOrientation attribute in activity and provides its orientation. In this example, we provide "portrait" orientation for MainActivity and "landscape" for SecondActivity.


1 Answers

Your calling to this.setState is wrong. Need to change it to be like:

handleChange: function() {
    var self = this;          // Store `this` component outside the callback
    if ('onorientationchange' in window) {
        window.addEventListener("orientationchange", function() {
            // `this` is now pointing to `window`, not the component. So use `self`.
            self.setState({   
                orientation: !self.state.orientation
            })
            console.log("onorientationchange");
        }, false);
    }
like image 93
Joy Avatar answered Sep 17 '22 11:09

Joy