Created
December 17, 2018 12:33
-
-
Save wiesson/b6957de6f01a8cb156a8d8750868f7bd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from "react"; | |
class TimeField extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
value: "00:00 am", | |
isValid: true, | |
hour: 0, | |
minute: 0 | |
}; | |
} | |
inputRef = React.createRef(); | |
handleChange = ev => { | |
const { value } = ev.target; | |
const isValid = /^([0]\d|[1][0-2]):([0-5]\d)\s?(?:AM|PM)$/i.test(value); | |
if (isValid) { | |
const date = parse(value, "hh:mm aa", new Date()); | |
console.log("Hours", date.getHours()); | |
console.log("Minutes", date.getMinutes()); | |
} | |
this.setState({ value, isValid }); | |
}; | |
handleKeyUp = ev => { | |
const { selectionStart } = ev.target; | |
const { current } = this.inputRef; | |
if (!current) { | |
return null; | |
} | |
if (selectionStart === 0) { | |
current.focus(); | |
current.setSelectionRange(0, 2); | |
} | |
if (selectionStart === 2 || selectionStart === 3) { | |
current.focus(); | |
current.setSelectionRange(3, 5); | |
} | |
}; | |
render() { | |
const { value, isValid } = this.state; | |
return ( | |
<div className="App"> | |
<input | |
ref={this.inputRef} | |
type="text" | |
value={value} | |
onChange={this.handleChange} | |
// onKeyUp={this.handleKeyUp} | |
// onFocus={this.handleKeyUp} | |
// onClick={this.handleKeyUp} | |
/> | |
<div>{isValid ? "ok" : "nope"}</div> | |
</div> | |
); | |
} | |
} | |
export default TimeField; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment