It's a pain to swipe months right until I get to the right year with react-dates
, is it possible to add some select for the year/month?
Asked
Active
Viewed 9,278 times
4

Evgenia Karunus
- 10,715
- 5
- 56
- 70
-
In case someone is unsure: Yes [self-answering is appreciated](https://stackoverflow.com/help/self-answer) – Jonas Wilms Sep 16 '18 at 19:51
2 Answers
16
Yes, it is possible since version react-dates@17.0.0! (relevant pull request).
npm install react-dates@latest
- You will likely need to update a few things as per the docs, because of the breaking changes (for me it was css mostly).
Then utilize the newly introduced
renderMonthElement
prop to write your custom month&year selectors, for example:import React from 'react'; import moment from 'moment'; import { SingleDatePicker } from 'react-dates'; class Main extends React.Component { state = { date: moment(), focused: true } renderMonthElement = ({ month, onMonthSelect, onYearSelect }) => <div style={{ display: 'flex', justifyContent: 'center' }}> <div> <select value={month.month()} onChange={(e) => onMonthSelect(month, e.target.value)} > {moment.months().map((label, value) => ( <option value={value}>{label}</option> ))} </select> </div> <div> <select value={month.year()} onChange={(e) => onYearSelect(month, e.target.value)}> <option value={moment().year() - 1}>Last year</option> <option value={moment().year()}>{moment().year()}</option> <option value={moment().year() + 1}>Next year</option> </select> </div> </div> render = () => <SingleDatePicker date={this.state.date} onDateChange={(date) => this.setState({ date })} focused={this.state.focused} onFocusChange={({ focused }) => this.setState({ focused })} renderMonthElement={this.renderMonthElement} /> }

Evgenia Karunus
- 10,715
- 5
- 56
- 70
7
To slightly tweak the @lakesare answer for those wanting to list out, say, the last 100 years for a birthday, here's a code snippet :
renderMonthElement = ({ month, onMonthSelect, onYearSelect }) => {
let i
let years = []
for(i = moment().year(); i >= moment().year() - 100; i--) {
years.push(<option value={i} key={`year-${i}`}>{i}</option>)
}
return (
<div style={{ display: "flex", justifyContent: "center" }}>
<div>
<select value={month.month()} onChange={e => onMonthSelect(month, e.target.value)}>
{moment.months().map((label, value) => (
<option value={value} key={value}>{label}</option>
))}
</select>
</div>
<div>
<select value={month.year()} onChange={e => onYearSelect(month, e.target.value)}>
{years}
</select>
</div>
</div>
)
}
render() {
return (
<SingleDatePicker
...
renderMonthElement={this.renderMonthElement}
/>
)
}
Modify the for loop on line 4 to print out whatever years you need.

efru
- 1,401
- 3
- 17
- 20
-
to make it more robust one can add ````i >= Math.max(0, moment().year() - numberOfYearsBack)```` in line 4. – Aman Godara Nov 06 '21 at 15:23