Created
January 23, 2018 19:48
-
-
Save bluzir/69192526e0db37112b353e39a6586c51 to your computer and use it in GitHub Desktop.
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 styled from "styled-components"; | |
import "react-dates/initialize"; | |
import "react-dates/lib/css/_datepicker.css"; | |
import { DayPickerRangeController } from "react-dates"; | |
const Button = styled.button` | |
border-radius: 4px; | |
border: 1px solid rgba(72, 72, 72, 0.2); | |
font-family: Circular, Helvetica Neue, Helvetica, Arial, sans-serif; | |
padding: 7px 16px; | |
font-size: 14px; | |
color: #383838; | |
background: transparent; | |
cursor: pointer; | |
`; | |
const getNumberOfMonths = () => { | |
if (window.matchMedia("(min-width: 992px)").matches) { | |
return 2; | |
} | |
if (window.matchMedia("(min-width: 768px)").matches) { | |
return 1; | |
} | |
return 4; | |
}; | |
export default class DatePicker extends React.Component { | |
state = { | |
focusedInput: "startDate", | |
startDate: null, | |
endDate: null, | |
isOpen: false | |
}; | |
datePickerToggle = () => { | |
this.setState(prevState => ({ isOpen: !prevState.isOpen })); | |
}; | |
componentWillReceiveProps(newProps) { | |
this.setState({ | |
focusedInput: newProps.startDate ? "endDate" : "startDate", | |
startDate: newProps.startDate, | |
endDate: newProps.endDate | |
}); | |
} | |
onDatesChange = ({ startDate, endDate }) => { | |
this.setState({ startDate: startDate, endDate: endDate }); | |
}; | |
onFocusChange = focusedInput => { | |
this.setState({ | |
// Force the focusedInput to always be truthy so that dates are always selectable | |
focusedInput: !focusedInput ? "startDate" : focusedInput | |
}); | |
}; | |
onReset = () => { | |
this.props.onApply({ | |
startDate: null, | |
endDate: null | |
}); | |
this.props.onClose(); | |
}; | |
onApply = () => { | |
this.props.onApply({ | |
startDate: this.state.startDate, | |
endDate: this.state.endDate | |
}); | |
}; | |
hasSelectedDates = () => { | |
return this.props.startDate || this.props.endDate; | |
}; | |
render() { | |
return ( | |
<div> | |
<Button onClick={this.datePickerToggle} highlighted={this.state.isOpen}> | |
Dates | |
</Button> | |
{this.state.isOpen && ( | |
<DayPickerRangeController | |
hideKeyboardShortcutsPanel | |
noBorder | |
startDate={this.state.startDate} | |
endDate={this.state.endDate} | |
onDatesChange={this.onDatesChange} | |
focusedInput={this.state.focusedInput} | |
onFocusChange={this.onFocusChange} | |
numberOfMonths={getNumberOfMonths()} | |
orientation={this.props.isMobile ? "verticalScrollable" : "horizontal"} | |
/>)} | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment