2

how to access react component state from jQuery "changeDate" event (of jqueryUI date) callback function.

var subheader = React.createClass({

    getInitialState: function () {
        return {
            msg: this.props.msg
        };
    },

    componentDidMount: function () {
        $('#date').datepicker({
            format: "dd/mm/yyyy"
        }).on("changeDate", function (e) {
            console.log(this.state.msg);
        });

    },
    render: function () {
        return (
                    // render HTML here.

        )
    }
});

but getting this.state is undefined. Please can any one help me.

Glen Swift
  • 10,962
  • 14
  • 43
  • 73
  • Possible duplicate of [How to access the correct \`this\` / context inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – James Brierley Apr 20 '16 at 09:25

1 Answers1

7

This problem is not specific for React but JavaScript in general.

You can solve it saving this somewhere in upper scope:

componentDidMount: function () {
    var self = this;
    $('#date').datepicker({
        format: "dd/mm/yyyy"
    }).on("changeDate", function (e) {
        console.log(self.state.msg);
    });
},

If you're using EcmaScript6 you can use arrow function:

componentDidMount: function () {
    $('#date').datepicker({
        format: "dd/mm/yyyy"
    }).on("changeDate", e => {
        console.log(this.state.msg);
    });
},
Community
  • 1
  • 1
Glen Swift
  • 10,962
  • 14
  • 43
  • 73