Search code examples
reactjsreact-datepicker

I can't have a beginning value for react-datepicker and still be able to change it from dropdown?


EDIT: I found the answer, check it below and add these together!

I'm trying to have the react-datepicker dropdown menu to show the current start_time when it's first loaded and then the user could choose a time they want from the dropdown. Time could then be submitted with a button (not relevant).

At the moment the time slot doesn't show placeholderText, it shows current time (my timezone) and it can change into whatever the user chooses. I've tried to put selected={null}, which shows the placeholderText correctly, but it then won't submit save user's chosen time.

If someone could help me get this to work, I'd appreciate it a lot! The placeholderText isn't important, as long as it shows start_time first and it can then be changed. Thanks in advance!

start_time = TIME data type from MySQL (XX:XX:XX)
reservationsData[0] = {start_time: 9.00} etc.
row = sets which start_time is given

class TimeClass extends Component {
  constructor(props) {
    super(props);
    this.state = {
      time: new Date()
    };
  }

  handleChange = time => {
    this.setState({
      time: time
    });
  }

  render() {
    let showThisFirst = this.props.reservationsData[this.props.row - 1].start_time;

    return (
      <div>
        <DatePicker
          selected={this.state.time}
          onChange={this.handleChange}
          placeholderText={moment(showThisFirst, "hh:mm:ss").format("HH.mm")}
          showTimeSelect
          showTimeSelectOnly
          timeIntervals={15}
          dateFormat="HH.mm"
          timeCaption="Time"
          getDefaultLocale="fi"
        />
      </div>
    );
  }
}

Visually:

|---------|    
|  09.00  | // looks like this when it loads, start_time
|---------|

|---------|    
|  09.00  | // choosing a time to replace 09.00
|---------|
|  08.30  |
|  08.45  |
|  09.00  | 
|  09.15  |
|  09.30  |
|  09.45  |
|  10.00  |
|   ...   |
|---------|

|---------|    
|  09.45  | // when the time is chosen, user changes the start_time
|---------| // no need to submit, just choose. Button next to it handles it

Solution

  • So, I found an answer myself!

    It was simple, just set selected={this.state.startTime} for the DataPicker and put startTime: time inside handleChange.

    In short:

    handleChange = time => {
      this.setState({
        startTime: time
      });
    }
    
    return (
      <DatePicker
        selected={this.state.startTime}
        onChange={this.handleChange}
        placeholderText={moment(dropPicker, "hh:mm:ss").format("HH.mm")}
      />
    );