Reputation: 2351
I am trying to open the react-datepicker on the click of an icon. For that, I am using customInput
parameter. The react-datepicker is getting opened on the click of the icon, but the onChange
handler is not getting the selected date. Here is my code:
<div className="date-icon">
<DatePicker
id="date-picker"
dateFormat="YYYY-MM-DD"
selected={this.state.startDate}
showMonthDropdown
onChange={this.handleDateChange.bind(this)}
customInput={<img src="/img/cal.svg" alt=""/>}
//includeDates={this.state.activityDates}
/>
<br/>
</div>
And here is the handleDateChange function
handleDateChange(date, event){
console.log(document.getElementById("date-picker").value)
}
I am getting undefined
on console log.
When I remove that customInput
parameter, then the date gets printed in the console as expected.
Upvotes: 1
Views: 4549
Reputation: 112787
The default input is an input
element, which has a value
. Your custom input <img src="/img/cal.svg" alt=""/>
is not an input element, and has no value
.
You could instead store the moment given to you in the onChange
handler and store that in state and use that instead.
Example
class App extends React.Component {
state = { selectedDate: moment() };
handleDateChange = m => {
this.setState({ selectedDate: m });
console.log(m.format("YYYY-MM-DD"));
};
render() {
return (
<DatePicker
id="date-picker"
dateFormat="YYYY-MM-DD"
selected={this.state.selectedDate}
showMonthDropdown
onChange={this.handleDateChange}
customInput={<img src="/img/cal.svg" alt=""/>}
/>
);
}
}
Upvotes: 3