Search code examples
javascriptreactjsinputmaterial-uitimepicker

How can I edit the value of the timepicker from the keyboard?


I have a material-ui-time-picker and I want to control this input, it works well, but I want to edit the time input from the keyboard and not when I click the input on the clock.

My code is :

import React, { Component } from "react";
import { TimePicker } from "material-ui-time-picker";
import { Input as Time, Dialog as Clock } from "@material-ui/core";

openDialog = () => this.setState({ isOpen: true });
  closeDialog = () => this.setState({ isOpen: false });
  handleDialogTimeChange = newValue => {
    const hours = newValue
      .getHours()
      .toString()
      .padStart(2, "0");
    const minutes = newValue
      .getMinutes()
      .toString()
      .padStart(2, "0");
    const textValue = hours + ":" + minutes;
    this.setState({ time: textValue });
  };
  handleKeyboardTimeChange = time => this.setState({ time });
  createDateFromTextValue = value => {
    const splitParts = value.split(":");
    return new Date(1970, 1, 1, splitParts[0], splitParts[1]);
  };
render() {

    return (

      <div>
        <Time
          value={this.state.time}
          onChange={this.handleKeyboardTimeChange}
          endAdornment={
            <InputAdornment position="end">
              <IconButton onClick={this.openDialog}>
                <AccessTime />
              </IconButton>
            </InputAdornment>
          }
          //}
        />
        <Clock maxWidth="xs" open={this.state.isOpen}>
          <TimePicker
            mode="24h"
            value={this.createDateFromTextValue(this.state.time)}
            onChange={this.handleDialogTimeChange}
            autoOk={true}
            cancelLabel=""
            okLabel=""
            placeholder=""
            disableUnderline={true}
          />
        </Clock>
      </div>
    );
  }

My sandbox: https://codesandbox.io/s/vm9wm19p27

When I run it, I get this input, but when I edit his value, the input will be disappeared.

How can I fix it ?


Solution

  • I've forked your sandbox and made a couple of adjustments. Though I've not fixed it - I'll just show you what's currently wrong.

    https://codesandbox.io/s/j24rqql9n9

    I modified two lines
    In your constructor, I added

    this.handleKeyboardTimeChange = this.handleKeyboardTimeChange.bind(this)
    

    And your handleKeyboardTimeChange:

    handleKeyboardTimeChange(event) {
      this.setState({ time: event.target.value });
    }
    

    This simply sets the state to exact value passed in from what you see there. No additional validation.