Ad

How To Correctly Use "time" Input Element?

- 1 answer

I have a react component that renders the following html:

        <input
          type="time"
          step="1"
          value={this.state.time}
          className="form-control"
          placeholder="Time"
          onChange={(ev) => {this.setState({time:ev.target.value})}
        />

This "sort of" works, but the problem is that I can't type double digit numbers in the input field. Let's say I want to type 00:23:00. I start out with a time field that looks like this:

00:00:00

next I click with the mouse on the middle pair of zeros. I push '2' on the keyboard. Now it will look like this:

00:02:00

However when I type '3' (no matter how fast I do this), what happens is my value looks like this:

00:03:00

while I would expect it to look like this:

00:23:00

If I remove the value attribute it all works as expected, but in that case I can't set a start value in my time field, which is rather annoying when editing existing content.

I guess the setState triggers a rerender of the component, making it behave weirdly.

Any ideas on how to fix this?

Ad

Answer

Fixed it myself. I was converting the 00:00:00 string (or whatever value it sent back to the code) in an integer representing a timestamp. In the value attribute I converted that integer back to the 00:00:00 representation. That seemed to generated the behaviour I described. If I just store the string as-is all works as expected.

Ad
source: stackoverflow.com
Ad