0
votes

I used bootstrap-datepicker in the past which has an option to have a month calendar stay static (inline) as shown here.

I am now using React (and am pretty new at it), and need a date-picker again. I decided to use react-bootstrap-date-picker however react-bootstrap-datepicker does not have an inline option.

I don't want to heavily hack into the css for react-bootstrap-datepicker, what is the best way to load a jQuery dependent library such as bootstrap-datepicker on react? Would this be bad practice?

Here is the JS(jQuery)/HTML code for loading the bootstrap-datepicker module.

<div id="datepicker" data-date="12/03/2012"></div>
<input type="hidden" id="my_hidden_input">

$('#datepicker').datepicker();

$('#datepicker').on('changeDate', function() {

    $('#my_hidden_input').val(
        $('#datepicker').datepicker('getFormattedDate')
    );

});

UPDATE:

So while this did workout in terms of rendering the bootstrap calendar, I am not able to get the event to fire when #my_hidden_input's value has been updated. I added an onChange event to detect the value change for the div in the render() function.

<div id="datepicker"></div> 

    <div id="#my_hidden_input" onChange={this.handleDate}>

</div> 

where the handleDate() function simply fires off a console.log(1);

1
Check out react-bootstrap-daterangepicker (npmjs.com/package/react-bootstrap-daterangepicker) instead, I think that is what you were looking for. Creates a React component wrapper for bootstrap daterangepicker and gives you access to all of the same options as the original. - Chase DeAnda
And here is an issue I opened with an example of how I add custom classes and styles to the date picker. github.com/skratchdot/react-bootstrap-daterangepicker/issues/… - Chase DeAnda

1 Answers

3
votes

The "React" way of initializing a jQuery plugin would be to do it in the componentDidMount lifecycle method.

componentDidMount(){
    $('#datepicker').datepicker();

    $('#datepicker').on('changeDate', function() {

        $('#my_hidden_input').val(
            $('#datepicker').datepicker('getFormattedDate')
        );

    });
}

Update: Adding what @klaasman said concerning destroying or unmounting plugins. Use the componentWillUnmount lifecycle method:

componentWillUnmount(){
    $('#datepicker').destroy();
}

Update 2: The onChange event isn't firing because you you didn't set the event to call the handleDate function. Here, you set the change event to an anonymous function:

$('#datepicker').on('changeDate', function() {

    $('#my_hidden_input').val(
        $('#datepicker').datepicker('getFormattedDate')
    );

});

Instead, you need to supply your handleDate function like so:

$('#datepicker').on('changeDate', this.handleDate);