Reputation: 6296
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?
Upvotes: 8
Views: 23388
Reputation: 56113
In my case the problem because I was also passing min and max attributes to the element, and changing one of those attribute values on the fly.
What it is that the HTML element implement has internal state (required to implement typing double digits); and that state is lost if the element is recreated.
So:
Upvotes: 0
Reputation: 6296
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.
Upvotes: 4
Reputation: 475
I tested your code in jsbin, but can not reproduce your problem.
Demo is here: http://jsbin.com/vujixe/edit?html,js,output
You can test it.
By the way, if you want to set a start value in your field, the commendatory method is getInitState
, just like my code in jsbin.
Second, setState
does trigger a rerender of the component.
Upvotes: 0