Search code examples
reactjsmaterial-uitimepicker

timepicker existing value is not prepopulating in the timepicker input


I am working on React timepicker component where I have to show the by default time as "4:00 PM" and whenever user saves the data already then I need to auto-populate the existing saved data but eventhough I have given 'value' attribute and then the state variable but still it is not showing the existing time in the 'timepicker' component.

What I tried:

I am getting a time value of myStateVariableTime="05:00PM"

<LocalizationProvider dateAdapter={AdapterDayjs}>
   <TimePicker label="Time"
     value={myStateVariableTime ? myStateVariableTime : dayjs('2024-09-27T16:00')}
     onChange={(newValue) => setMyStateVariableTime(newValue)}
   />
</LocalizationProvider>

I have tried with below also but didn't work though

value={myStateVariableTime ? dayjs(myStateVariableTime) : dayjs('2024-09-27T16:00')}
value={myStateVariableTime ? dayjs(myStateVariableTime).format('hh:mm A') : dayjs('2024-09-27T16:00')}

Any help would be greatful. Thanks.


Solution

  • Below fix worked for me

    const handleTimeChange = (time) => {
        let timeValue = default4PM
        if(time) {
            timeValue = dayjs(time).format('hh:mm A')
        }
        setMyTimePicker(timeValue)
    }
    const default4PM = dayjs().hour(16).minute(0).second(0).format('hh:mm A')
    <TimePicker label="Time" value={myStateVariableTime ? dayjs(myStateVariableTime, 'hh:mm A') : default4PM}
       onChange={(newValue) => setMyTimePicker(newValue)}
       slotProps={{
                   textField: {
                      readOnly: true
                   },
                 }}
    />