Created
December 28, 2016 03:43
-
-
Save tiendq/6c525ff900fd51f51bca17de7376fe03 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 React from "react"; | |
const numeral = require("numeral"); | |
const BACKSPACE_KEY = 8, TAB_KEY = 9, ENTER_KEY = 13, NUMBER_0 = 48, NUMBER_9 = 57; | |
class KilometerInput extends React.Component { | |
constructor() { | |
super(); | |
this.keyPressHandler = this.keyPressHandler.bind(this); | |
this.keyDownHandler = this.keyDownHandler.bind(this); | |
} | |
keyDownHandler(event) { | |
let key = event.which; | |
if (key >= NUMBER_0 && key <= NUMBER_9 || TAB_KEY === key || ENTER_KEY === key) | |
return true; | |
if (BACKSPACE_KEY === key) | |
return this.props.onKeyPress("", true); | |
// Only can cancel event in keydown handler. | |
event.preventDefault(); | |
} | |
keyPressHandler(event) { | |
let key = event.which; | |
if (key >= NUMBER_0 && key <= NUMBER_9) | |
return this.props.onKeyPress(event.key); | |
} | |
componentDidMount() { | |
if (this.inputField) | |
this.inputField.focus(); | |
} | |
render() { | |
let km = this.props.kilometers ? numeral(parseInt(this.props.kilometers, 10)).format("0,0") : ""; | |
return ( | |
<input type="text" id="kilometers" | |
value={km} | |
ref={element => this.inputField = element} | |
onKeyPress={this.keyPressHandler} | |
onKeyDown={this.keyDownHandler} | |
className="form-control" | |
placeholder="e.g. 4500" | |
maxLength="7" | |
autoComplete="false" /> | |
); | |
} | |
} | |
KilometerInput.propTypes = { | |
kilometers: React.PropTypes.string.isRequired, | |
onKeyPress: React.PropTypes.func.isRequired | |
}; | |
export default KilometerInput; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment