import {addDays, format, isAfter, isBefore, startOfDay} from 'date-fns'; import React, {Component, Fragment} from 'react'; import classes from 'classnames'; import DatePickerDialog from './DatePickerDialog'; import {Dialog} from 'core'; import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; import PropTypes from 'prop-types'; import './index.css'; export default class DatePicker extends Component { static propTypes = { className: PropTypes.string, dateFormat: PropTypes.string, endDate: PropTypes.instanceOf(Date), isRange: PropTypes.bool, maxDate: PropTypes.instanceOf(Date), minDate: PropTypes.instanceOf(Date), name: PropTypes.string, onSelect: PropTypes.func.isRequired, startDate: PropTypes.instanceOf(Date), }; static defaultProps = { dateFormat: 'YYYY-MM-DD', startDate: startOfDay(new Date()), endDate: addDays(new Date(), 1), }; constructor(props) { super(props); const startDate = !props.minDate || isAfter(props.startDate, props.minDate) ? props.startDate : props.minDate; const endDate = !props.maxDate || isBefore(props.endDate, props.maxDate) ? props.endDate : props.maxDate; this.state = { startDate: startOfDay(startDate), endDate: props.isRange ? startOfDay(endDate) : undefined, }; } // This is my custom Dialog opener // it opens a Bulma modal with a modal-card onClick = () => Dialog({ title: '', styles: { dialog: classes('date-picker-dialog', { 'date-picker-dialog-range': this.props.isRange, }), }, cancel: this.props.isRange ? 'Cancel' : undefined, submit: this.props.isRange ? 'Save' : undefined, custom: { View: DatePickerDialog, props: { maxDate: this.props.maxDate, minDate: this.props.minDate, isRange: this.props.isRange, startDate: this.state.startDate, endDate: this.state.endDate, }, }, }).then(this.onSelect); onSelect = event => event && this.setState( {startDate: event.startDate, endDate: event.endDate}, () => this.props.onSelect({ name: this.props.name, startDate: this.state.startDate, endDate: this.state.endDate, }) ); render() { const {className, dateFormat, isRange} = this.props; const {startDate, endDate} = this.state; const formattedStartDate = format(startDate, dateFormat); const formattedEndDate = isRange ? format(endDate, dateFormat) : ''; return (
{formattedStartDate} {isRange && ( {formattedEndDate} )}
); } }