| 1 |
import { useState } from 'react'; |
| 2 |
import { Split, SplitItem, DatePicker, isValidDate, yyyyMMddFormat } from '@patternfly/react-core'; |
| 3 |
|
| 4 |
export const DatePickerRange: React.FunctionComponent = () => { |
| 5 |
const [from, setFrom] = useState<Date | undefined>(); |
| 6 |
const [to, setTo] = useState<string>(''); |
| 7 |
|
| 8 |
const toValidator = (date: Date) => |
| 9 |
isValidDate(from) && date >= from ? '' : 'The "to" date must be after the "from" date'; |
| 10 |
|
| 11 |
const onFromChange = (_event: React.MouseEvent<HTMLElement>, _value: string, date: Date) => { |
| 12 |
setFrom(new Date(date)); |
| 13 |
if (isValidDate(date)) { |
| 14 |
date.setDate(date.getDate() + 1); |
| 15 |
setTo(yyyyMMddFormat(date)); |
| 16 |
} else { |
| 17 |
setTo(''); |
| 18 |
} |
| 19 |
}; |
| 20 |
|
| 21 |
const onToChange = (_event: React.MouseEvent<HTMLElement>, _value: string, date: Date) => { |
| 22 |
if (isValidDate(date)) { |
| 23 |
setTo(yyyyMMddFormat(date)); |
| 24 |
} |
| 25 |
}; |
| 26 |
|
| 27 |
return ( |
| 28 |
<Split> |
| 29 |
<SplitItem> |
| 30 |
<DatePicker onChange={onFromChange} aria-label="Start date" placeholder="YYYY-MM-DD" /> |
| 31 |
</SplitItem> |
| 32 |
<SplitItem style={{ padding: '6px 12px 0 12px' }}>to</SplitItem> |
| 33 |
<SplitItem> |
| 34 |
<DatePicker |
| 35 |
value={to} |
| 36 |
onChange={onToChange} |
| 37 |
isDisabled={!isValidDate(from)} |
| 38 |
rangeStart={from} |
| 39 |
validators={[toValidator]} |
| 40 |
aria-label="End date" |
| 41 |
placeholder="YYYY-MM-DD" |
| 42 |
/> |
| 43 |
</SplitItem> |
| 44 |
</Split> |
| 45 |
); |
| 46 |
}; |