4

Currently, I'm creating a mini-project in order to learn React. I'm using React Datepicker for my booking page. It's easy to save a chosen date in state:

state = {
            startDate: new Date(),
            time: null 
} 
handleChange = (date) => {
    this.setState( {startDate: date} )         
}
<DatePicker
        selected={this.state.startDate}
        locale="ru"
        onChange={this.handleChange}
        minTime={setHours(setMinutes(new Date(), 0), 9)}
        maxTime={setHours(setMinutes(new Date(), 0), 22)}
        showTimeSelect
        timeIntervals={60}
        inline
/>

But I don't understand how to save time in the state as well. If a user doesn't choose the time, the current time will be saved but it's not what I want. I need to have "time" as a requirement and save it correctly in the state.

I would appreciate any help!

Han
  • 3,272
  • 3
  • 24
  • 39
Xenia
  • 85
  • 1
  • 8

2 Answers2

1

set your state as below

  state={
        startDate:new Date()
        }

        return (
        <DatePicker
      selected={startDate}
      onChange={date => setStartDate(date)}
      timeInputLabel="Time:"
      dateFormat="MM/dd/yyyy h:mm aa"
      showTimeInput
    />
      );
Arpit Vyas
  • 2,118
  • 1
  • 7
  • 18
  • Thank you but what I need is to have "time" and "date" separately in my state. – Xenia Nov 06 '19 at 07:12
  • @xenia I edited my code please check. now, you will get time & date in onChange. – Arpit Vyas Nov 06 '19 at 08:27
  • Thank you for your work! Anyway, I don't understand how i will get time & date separately in state, if it's only "startDate" there. What i need is "state = { day: "", time: "" } – Xenia Nov 06 '19 at 08:49
0

Well, in the end I had to add my own time component and use it.

Xenia
  • 85
  • 1
  • 8