Sunday, February 21, 2021

How to open/close react-datepicker on a condition?


 React Date picker allows the user to select the date and time with a nice beautiful Interface. It provides you fine control over the User Interface and a lot of features to customize it according to your need. You can find all the possible options with well-explained examples on their website at https://reactdatepicker.com/, but recently  I was working on a project where I need to open/close the date-picker on certain conditions, I tried a lot but didn't find any good way to achieve it, finally, I achieved it by using ref in react

Before I explain here are some useful links

Github Repo: https://github.com/guide-father/open-close-react-datepicker-on-condition

Preview: https://github-ze2knr.stackblitz.io

Stackblitz: https://stackblitz.com/edit/github-ze2knr?file=src/calendar.js



Calendar.js

import React from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";


class Calendar extends React.Component {

constructor() {
super()
this.state = {
selectedDate: new Date(),
isOpen:false
}
this.pickerRef = React.createRef() //Defining Ref
}
SetDate = (date) => {
this.setState({
selectedDate: date
})
}
ChangeState = () => {
this.pickerRef.current.setOpen(!this.state.isOpen)
this.setState({
isOpen:!this.state.isOpen
})
}
render() {
return (
<div>
<div>
<button onClick={this.ChangeState}>
                            {this.state.isOpen?"Close":" Open"}
                    </button>
</div>
<div>
<DatePicker
selected={this.state.selectedDate}
onChange={this.SetDate}
dateFormat="yyyy/MM/dd"
ref={this.pickerRef}
/>
</div>

</div>
)
}
}

export default Calendar


Declare a reference by

this.pickerRef = React.createRef()

and assign the reference to the DatePicker 
now you can have fine control over the state of datepicker by 

this.pickerRef.current.setOpen(state)