Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React DatePicker how to open datepicker on click of icon

Tags:

reactjs

redux

Trying to open datepicker on click of icon of react-datepicker component, I have gone through their docs and issues links but found that its not much useful.

<DatePicker
        {...startDateOpts}
        id='abc'
        maxDate={moment()}
        onChange={this.handleStartChange}
        placeholderText='Start Date'
        popoverAttachment={smallScreen ? 'bottom center' : undefined}
        popoverTargetAttachment={smallScreen ? 'top center' : undefined}
        popoverTargetOffset={smallScreen ? '0px 0px' : undefined}
      />

enter image description here

I tried from React-datepicker docs link but no luck.

like image 914
Jayant Patil Avatar asked Oct 18 '16 08:10

Jayant Patil


2 Answers

If you want to programmatically open the datepicker or if you just don't want to use a <label> wrapper you can set a ref to the datepicker component and use setOpen(bool) to open it. Notice that since we're using refs, the component should be stateful.

Example:

openDatepicker = () => this._calendar.setOpen(true);


render() {
    <Datepicker
        {...datepickerProps}
        ref={(c) => this._calendar = c} />

    <img src={iconImg} onClick={this.openDatepicker} />
}

There is currently an open issue on the datepicker's Github stating that this is missing from the docs.

like image 76
fabio.sang Avatar answered Sep 20 '22 19:09

fabio.sang


Just wrap DatePicker with label. All click inside label call focus on input, that open calendar.

<label>
    <DatePicker/>
</label>
like image 45
tre Avatar answered Sep 22 '22 19:09

tre