Skip to content

Instantly share code, notes, and snippets.

@RedHatter
Last active August 4, 2021 02:14
Show Gist options
  • Save RedHatter/482d6370f9f9546498890b348636aacb to your computer and use it in GitHub Desktop.
Save RedHatter/482d6370f9f9546498890b348636aacb to your computer and use it in GitHub Desktop.
Range and multi select for @dmtrKovalenko/material-ui-pickers
import React, { useState, useContext, useRef } from 'react'
import { DatePicker } from 'material-ui-pickers'
import { MuiPickersContext } from 'material-ui-pickers'
export default function DateMultiPicker({
value,
onChange,
labelFunc,
format,
emptyLabel,
onClose,
...props
}) {
const [dates, setDates] = useState(value)
const utils = useContext(MuiPickersContext)
function renderDay(day, selectedDate, dayInCurrentMonth, dayComponent) {
return React.cloneElement(dayComponent, {
onClick: e => {
e.stopPropagation()
const i = dates.findIndex(d => utils.isSameDay(d, day))
if (i >= 0) {
const nextDates = [...dates]
nextDates.splice(i, 1)
setDates(nextDates)
} else {
setDates([...dates, day])
}
},
selected: !!dates.find(d => utils.isSameDay(d, day))
})
}
const formatDate = date => utils.format(date, format || utils.dateFormat)
return (
<DatePicker
{...props}
value={dates[0]}
renderDay={renderDay}
onClose={() => {
onChange(dates)
if (onClose) onClose()
}}
onChange={() => {}}
onClear={ () => {
setDates([])
onChange([])
}}
labelFunc={(date, invalid) =>
labelFunc
? labelFunc(dates, invalid)
: date && dates.length > 0
? dates.map(formatDate).join(', ')
: emptyLabel || ''
}
/>
)
}
import React, { useState, useContext, useRef } from 'react'
import { DatePicker } from 'material-ui-pickers'
import { MuiPickersContext } from 'material-ui-pickers'
import withStyles from '@material-ui/core/styles/withStyles'
import { styles as dayStyles } from 'material-ui-pickers/DatePicker/components/Day'
import clsx from 'clsx'
function DateRangePicker({
classes,
value,
onChange,
labelFunc,
format,
emptyLabel,
autoOk,
onClose,
...props
}) {
const [begin, setBegin] = useState(value[0])
const [end, setEnd] = useState(value[1])
const [hover, setHover] = useState(undefined)
const picker = useRef()
const utils = useContext(MuiPickersContext)
const min = Math.min(begin, end || hover)
const max = Math.max(begin, end || hover)
function renderDay(day, selectedDate, dayInCurrentMonth, dayComponent) {
return React.cloneElement(dayComponent, {
onClick: e => {
e.stopPropagation()
if (!begin) setBegin(day)
else if (!end) {
setEnd(day)
if (autoOk) {
onChange([begin, day].sort())
picker.current.close()
}
} else {
setBegin(day)
setEnd(undefined)
}
},
onMouseEnter: e => setHover(day),
className: clsx(classes.day, {
[classes.hidden]: dayComponent.props.hidden,
[classes.current]: dayComponent.props.current,
[classes.isDisabled]: dayComponent.props.disabled,
[classes.isSelected]: day >= min && day <= max,
[classes.beginCap]: utils.isSameDay(day, min),
[classes.endCap]: utils.isSameDay(day, max)
})
})
}
const formatDate = date => utils.format(date, format || utils.dateFormat)
return (
<DatePicker
{...props}
value={begin}
renderDay={renderDay}
onClose={() => {
onChange([begin, end].sort())
if (onClose) onClose()
}}
onChange={() => {}}
onClear={() => {
setBegin(undefined)
setEnd(undefined)
setHover(undefined)
onChange([])
}}
ref={picker}
labelFunc={(date, invalid) =>
labelFunc
? labelFunc([begin, end].sort(), invalid)
: date && begin && end
? `${formatDate(begin)} - ${formatDate(end)}`
: emptyLabel || ''
}
/>
)
}
export const styles = theme => {
const base = dayStyles(theme)
return {
...base,
day: {
...base.day,
margin: 0,
width: '40px',
borderRadius: '0'
},
beginCap: {
borderRadius: '50% 0 0 50%'
},
endCap: {
borderRadius: '0 50% 50% 0'
}
}
}
export default withStyles(styles, { name: 'DateRangePicker' })(DateRangePicker)
@Germain67
Copy link

Any plan on making this available on npm?
Would be really nice! :)

@TrejGun
Copy link

TrejGun commented May 5, 2019

onChange([begin, end].sort())

Array.prototype.sort() will not work as you're hoping. The MDN docs state that if you omit a custom sort function:

The array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

This means that each date will be toString-ed to a date string such as Sun Aug 21 2016 00:00:00 GMT-0600 (MDT) first, then each character, starting from the left, will have it's Unicode point value compared one at a time. This results in unexpected behavior in the sort, since it will essentially sort the array by days of the week first instead of absolute time of each date.

onChange([begin, end].sort((a, b) => a - b))

@TrejGun
Copy link

TrejGun commented May 7, 2019

also this fixes selected range when it is only one day

    beginCap: {
      borderTopLeftRadius: "50%",
      borderBottomLeftRadius: "50%",
    },
    endCap: {
      borderTopRightRadius: "50%",
      borderBottomRightRadius: "50%",
    },

@ardiansyaherwin
Copy link

@RedHatter do these two files have to be put together? I've tried the Range one, and use these code block to call the component:
<DateRangePicker value={columnDef.tableData.filterValue || null} onChange={onDateInputChange} format={'yyyy/MM/dd'} onClose={onDateInputChange} autoOk />

but it came up with this error:
Uncaught TypeError: Cannot read property '0' of null

here's the screenshot
http://tinyurl.com/y68qbrgr

@Angelk90
Copy link

Angelk90 commented Nov 4, 2019

@RedHatter: You could post an example on codesandbox.io?

@sibelius
Copy link

is there an updated gist of this, using latest version of material-ui-pickers?

@RedHatter
Copy link
Author

RedHatter commented Dec 2, 2019

I'm sorry for not supporting this. I don't use material-ui-pickers anymore or even react as a whole (in favor of svelte). This was simply intended as a quick hack that others could modify for their use case. Hence why it's a gist not an npm package. It looks like later version of material-ui-pickers changed enough as to break this. I don't have plans to to update this but if anyone else wants to take a crack at it feel free.

@rzfortes
Copy link

rzfortes commented Feb 13, 2020

how to use the labelFunc property? i'm trying to change the label in which if the start date and end date is the same, the label should only be date.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment