Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS Ant Design - Open DatePicker on button click

I am using ant design framework for ReactJS, where I am trying to find a solution to open DatePicker on button click, however this seems not possible with the framework component, I have tried to use third party DatePicker but it doesn't work well with it.

My requirement is to have a simple input and beside of it there will be a button, on clicking the button DatePicker should popup..

This is my unfinished demo

If anyone has worked on such solution, please help.

Thanks.

like image 822
iphonic Avatar asked Dec 18 '22 20:12

iphonic


2 Answers

DatePicker has an open prop that you can set to a boolean value. Add an onClick event to your button and then you can toggle the state of the datepicker.

I don't want to show that DatePicker input box, and choosing date to fill value in other Input field, any solution?

Without me detailing the styling part of this problem you can use the onChange event to set the value of the other input.

constructor(props) {
    super(props);
    this.state = {
        pickerOpen: false,
        selectedDate: null
    }
}

togglePicker = () => {
    this.setState({pickerOpen: !this.state.pickerOpen});
}

handleChange = selectedDate => {
    this.setState({selectedDate});
}

const { pickerOpen, selectedDate } = this.state;
<Input value={selectedDate && moment(selectedDate).format('YYYY-MM-DD')}/>
<DatePicker open={pickerOpen} onChange={this.handleChange}/>
<Button onClick={this.togglePicker}>
like image 149
wdm Avatar answered Dec 20 '22 10:12

wdm


You can use the open field in antd Datepicker to toggle the datepicker on button click.

<DatePicker
   open={this.state.openDatePicker}
   onOpenChange={this.datePickerStatus}
/>
<Button
   type="primary"
   style={{ marginLeft: "100px" }}
   onClick={this.toggleDatePicker}
>
  <Icon type="calendar" theme="outlined" />
</Button>

You can toggle the open field using the function toggleDatePicker called on button click:

toggleDatePicker = () => {
  this.setState(prevState => ({
    openDatePicker: !prevState.openDatePicker
  }));
};

You might also want to close the date picker on clicking outside, this can be achieved by:

hideDatePicker = () => {
  this.setState({
    openDatePicker: false
  });
};

datePickerStatus = status => {
  if (!status) {
    this.hideDatePicker();
  }
};

You can find the live example linked here

like image 20
Agney Avatar answered Dec 20 '22 10:12

Agney