Diablo3093
Diablo3093

Reputation: 1063

Handling the screen orientation change in 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 .

Upvotes: 7

Views: 19187

Answers (1)

Joy
Joy

Reputation: 9560

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);
    }

Upvotes: 6

Related Questions