2

I am using MUI Time picker with date-fns adapter (<LocalizationProvider dateAdapter={AdapterDateFns}>) to add / edit time.

When time picker is empty, entering new time works correctly. However, when editing an existing time entry, it is impossible to correctly change any value without cursor jumping around and values defaulting to 0 etc.

Here is a code sandbox with issue, and below is a gif of weird edit behavior:

time-picker-edit

This may be similar to issue mentioned in this question, which still does not have any answers.

Is my code wrong, or MUI / date-fns are the culprits here? Any help is appreciated.

EDIT

MUI's examples all use dayjs, not date-fns. But, date-fns is being used in many other parts of this project. Using another library just for this field seems wrong, and wasteful. completely switching over to dayjs (as mentioned by @sachila-ranawaka below) will be the last resort. I am looking for solutions which use date-fns.

Olivier Tassinari
  • 8,238
  • 4
  • 23
  • 23
Swapnil Luktuke
  • 10,385
  • 2
  • 35
  • 58

2 Answers2

1

use AdapterDayjs in the dateAdapter

import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";

<LocalizationProvider dateAdapter={AdapterDayjs}>

Demo

Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
  • date-fns is being used in many other parts of this project. using another library just for this seems wrong, and wasteful. completely switching over to dayjs will be our last resort. thank you. I will updated my question with this comment. – Swapnil Luktuke Dec 13 '22 at 14:24
1

I was able to get it working. Perhaps there's an issue with your top level App.js code.

Here's what I did (MUI 5):

timepicker.tsx

import { TextField } from '@mui/material'
import { LocalizationProvider } from '@mui/x-date-pickers'
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns'
import { TimePicker as MuiTimePicker } from '@mui/x-date-pickers/TimePicker'

interface ITimePicker {
  time: Date | null
  setTime?: (time: Date | null) => void
}

export function TimePicker({ time, setTime }: ITimePicker) {
  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <MuiTimePicker
        value={time}
        onChange={(newValue) => {
          setTime?.(newValue)
        }}
        renderInput={(props) => <TextField {...props} />}
      />
    </LocalizationProvider>
  )
}

parent.tsx

const [time, setTime] = useState<Date | null>(null)

<TimePicker
  time={time}
  setTime={setTime}
/>
Edwin
  • 380
  • 1
  • 4
  • 18