i'm using this plugin in my project. https://reactdatepicker.com
There is have some prop showTimeSelect
this prop takes boolean value and hide or show time picker.
I'm trying to give option to user about selecting time picker, so i tried to make some onClick event and make this prop conditional.
But it's work sometimes, sometimes not..
I don't understand where is the problem here is my code:
import React from "react";
import ReactDOM from "react-dom";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import "./styles.css";
class App extends React.Component {
state = {
startDate: new Date()
};
handleChange = date => {
this.setState({
startDate: date,
showTime: false
});
};
showTimeSelection = () => {
this.setState({
showTime: !this.state.showTime
});
};
render() {
return (
<div>
<DatePicker
selected={this.state.startDate}
onChange={this.handleChange}
showTimeSelect={this.state.showTime}
>
{" "}
<div>
<a onClick={() => this.showTimeSelection()}>
TOGGLE TIME SELECTION
</a>
</div>{" "}
</DatePicker>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
and here is the codesandbox example
You can try on codeSandBox it's sometimes work directly sometimes you need to click outside of datepicker and click inside again.
I have noticed it only works if showTimeSelect
is true
before the DatePicker
is going to be displayed. So, before closing DatePicker
you have to set showTimeSelect
to true. you can do it in prop onClickOutside
state = {
startDate: new Date(),
showTime: true
};
handleChange = date => {
this.setState({
startDate: date
});
};
showTimeSelection = () => {
this.setState({
showTime: !this.state.showTime
});
};
render() {
const { startDate, showTime } = this.state;
return (
<div>
<DatePicker
selected={startDate}
onChange={this.handleChange}
showTimeSelect={showTime}
onClickOutside={() => this.setState({ showTime: true })}
>
<div onClick={this.showTimeSelection} style={{ cursor: "pointer" }}>
<h4>TOGGLE TIME SELECTION</h4>
</div>
</DatePicker>
</div>
);
}
}
check out code sandbox . check out two other useful props onCalendarClose
and onCalendarOpen