Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datepicker attached to a React input component

In case of absence of native <input type="date"> support, I'd like to polyfill all the date inputs with datepicker widgets; for example, jQuery UI datepickers.

See the demo here. In Google Chrome it renders native date inputs, while in Firefox (v32.0.3) the jQuery UI widgets get deployed. That's exactly where I'm having a problem. All the manual changes in the input (keyboard edits) get reflected in the datepicker widget just fine. However, the other way around, if I select a day in the widget calendar, the new value doesn't get picked up by the underlying React component. In the demo you'll notice that in Chrome, on a date selection, the other date gets auto-adjusted. That functionality is broken for datepickers in Firefox. React has no idea that values change.

Following this advice, I've added

componentDidMount: function(e) {
    this.getDOMNode().addEventListener(
        'change',
        function (e) { console.dir(e); }
    );
},

to my DateInput component class. However, it never gets called on widget selections. How can I make it work?

The full non-compressed source code of the demo linked above is available here.

like image 721
Ivan Krechetov Avatar asked Sep 30 '14 12:09

Ivan Krechetov


1 Answers

The solution is doing everything over jQuery, and not over the DOM directly:

var isPolyfilled = function () {
        return (window && window.$ && window.$.datepicker);
    };

module.exports = React.createClass({
    ...

    componentDidMount: function () {
        setTimeout(function () {
            if (isPolyfilled()) {
                window.$(this.getDOMNode()).datepicker();
                window.$(this.getDOMNode()).on('change', this.handleEdit);
            }
        }.bind(this), 500);
    },

    componentWillUnmount: function () {
        if (isPolyfilled()) {
            window.$(this.getDOMNode()).off();
        }
    }

    ...
};

The complete source code is on GitHub.

like image 54
Ivan Krechetov Avatar answered Sep 29 '22 11:09

Ivan Krechetov