Reputation: 11202
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?
Upvotes: 4
Views: 10558
Reputation: 1470
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.
Upvotes: 7
Reputation: 11202
Yes, it is possible since version [email protected]! (relevant pull request).
npm install react-dates@latest
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}
/>
}
Upvotes: 16