React-datepicker: Can't close popup programmatically

Created on 31 Jul 2020  路  5Comments  路  Source: Hacker0x01/react-datepicker

Describe the bug
User can't close popup programmatically

To Reproduce

  1. Click on any picker (a popup will show)
  2. Assuming there is a cancel button, what code should that button run?

onBlur is called when the user clicks outside, but my goal is to close it programmatically. Thanks in advance!

Most helpful comment

First way: use refs (remember that refs are not available before picker is rendered first!)

datepickerRef = React.createRef();

onCloseButton = () => {
  this.datepickerRef.current.setOpen(false);
}

render() {
    return <DatePicker ref={this.datepickerRef} />;
}

Second way: use open prop:

render() {
    return <DatePicker open={this.state.shouldShowDatepicker} />;
}

All 5 comments

First way: use refs (remember that refs are not available before picker is rendered first!)

datepickerRef = React.createRef();

onCloseButton = () => {
  this.datepickerRef.current.setOpen(false);
}

render() {
    return <DatePicker ref={this.datepickerRef} />;
}

Second way: use open prop:

render() {
    return <DatePicker open={this.state.shouldShowDatepicker} />;
}

Thanks @kzotoff it is working as expected! I used the ref way since IMO it's a better approach to my problem.

@kzotoff:
Hi,
The open/close programmatically worked for me. But after closing by setOpen, the selected value was reset too.
How to prevent this unexpected reset action?

@ningo-agilityio:
Have no idea ) If you need to remember that value I think that's a good idea to store it by yourself and restore when opening datepicker, and don't rely on component which is technically a blackbox.

@kzotoff: Ok, let me check around. Thanks for your answer ^^

Was this page helpful?
0 / 5 - 0 ratings

Related issues

carmouche picture carmouche  路  3Comments

jjjss94 picture jjjss94  路  3Comments

dhruvparmar372 picture dhruvparmar372  路  3Comments

tamitutor picture tamitutor  路  3Comments

ahribori picture ahribori  路  3Comments