Created
May 23, 2019 17:30
-
-
Save shiningjason/4eb3a37cfa95b97b9b601f761debd26d to your computer and use it in GitHub Desktop.
Custom DateRangePicker with ant design
This file contains hidden or 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 { Col, DatePicker, Row } from 'antd' | |
| import moment from 'moment' | |
| import { arrayOf, func, instanceOf, string } from 'prop-types' | |
| import React, { useEffect, useRef, useState } from 'react' | |
| const isSameDate = (date1, date2) => | |
| date1 === date2 || (date1 && date1.isSame(date2)) | |
| const isSameDateRange = (range1, range2) => | |
| isSameDate(range1[0], range2[0]) && isSameDate(range1[1], range2[1]) | |
| export default function DateRangePicker({ | |
| format, | |
| placeholder, | |
| defaultValue, | |
| value = defaultValue, | |
| disabledDate, | |
| onChange | |
| }) { | |
| const prevValueRef = useRef(value) | |
| const [begin, setBegin] = useState(value[0]) | |
| const [end, setEnd] = useState(value[1]) | |
| useEffect(() => { | |
| const nextValue = begin && end ? [begin, end] : [null, null] | |
| if (isSameDateRange(nextValue, value)) return | |
| prevValueRef.current = nextValue | |
| onChange(nextValue) | |
| }, [begin, end]) | |
| useEffect(() => { | |
| const prevValue = prevValueRef.current | |
| if (isSameDateRange(value, prevValue)) return | |
| prevValueRef.current = value | |
| setBegin(value[0]) | |
| setEnd(value[1]) | |
| }, [value]) | |
| const disabledBeginDate = date => | |
| (end && date.isAfter(end)) || disabledDate('begin', date, [begin, end]) | |
| const disabledEndDate = date => | |
| (begin && date.isBefore(begin)) || disabledDate('end', date, [begin, end]) | |
| return ( | |
| <Row type="flex" gutter={8}> | |
| <Col xs={12}> | |
| <DatePicker | |
| style={{ width: '100%' }} | |
| format={format} | |
| placeholder={placeholder[0]} | |
| value={begin} | |
| disabledDate={disabledBeginDate} | |
| onChange={v => setBegin(v)} | |
| /> | |
| </Col> | |
| <Col xs={12}> | |
| <DatePicker | |
| style={{ width: '100%' }} | |
| format={format} | |
| placeholder={placeholder[1]} | |
| value={end} | |
| disabledDate={disabledEndDate} | |
| onChange={v => setEnd(v)} | |
| /> | |
| </Col> | |
| </Row> | |
| ) | |
| } | |
| DateRangePicker.defaultProps = { | |
| format: 'YYYY/MM/DD', | |
| placeholder: ['Begin date', 'End date'], | |
| defaultValue: [null, null], | |
| disabledDate: () => false | |
| } | |
| DateRangePicker.propTypes = { | |
| format: string, | |
| placeholder: arrayOf(string), | |
| defaultValue: arrayOf(instanceOf(moment)), | |
| value: arrayOf(instanceOf(moment)), | |
| disabledDate: func, | |
| onChange: func | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment