Created
June 11, 2018 10:40
-
-
Save hosembafer/07eb59c78ae6391815070e5d4e94c2f3 to your computer and use it in GitHub Desktop.
react-day-picker range + single days selection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import ReactDOM from "react-dom"; | |
import DayPicker from "react-day-picker"; | |
import DayPickerInput from "react-day-picker/DayPickerInput"; | |
import "react-day-picker/lib/style.css"; | |
class Example extends React.Component { | |
state = { | |
selectedDays: [], | |
start: null | |
}; | |
getDateArray = (start, end) => { | |
var arr = new Array(); | |
var dt = new Date(start); | |
while (dt <= end) { | |
arr.push(new Date(dt)); | |
dt.setDate(dt.getDate() + 1); | |
} | |
return arr; | |
}; | |
handleDayClick = (event, date, action) => { | |
if (this.state.start) { | |
var dateArr = this.getDateArray(this.state.start, date); | |
this.setState({ | |
selectedDays: [...this.state.selectedDays, ...dateArr], | |
start: null, | |
}); | |
} | |
else if (event.shiftKey) { | |
this.setState({ selectedDays: [...this.state.selectedDays, date] }); | |
this.setState({ | |
start: date | |
}); | |
} | |
else { | |
this.setState({ selectedDays: [...this.state.selectedDays, date] }); | |
} | |
}; | |
renderDay = date => { | |
return ( | |
<div onClick={event => this.handleDayClick(event, date, "single")}> | |
{date.getDate()} | |
</div> | |
); | |
}; | |
render() { | |
const { selectedDays } = this.state; | |
return ( | |
<div> | |
<h3>DayPicker</h3> | |
<DayPicker | |
selectedDays={selectedDays} | |
numberOfMonths={12} | |
renderDay={this.renderDay} | |
/> | |
<h3>DayPickerInput</h3> | |
<DayPickerInput placeholder="DD/MM/YYYY" format="DD/MM/YYYY" /> | |
</div> | |
); | |
} | |
} | |
ReactDOM.render(<Example />, document.getElementById("root")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment