class Input extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: "",
keycode: "",
addKeyUp: true,
keyval: ""
};
}
keyEventHandler = e => {
const CurrentKeyCode = Number(e.keyCode) || Number(e.which);
console.log(CurrentKeyCode, e.target.value);
this.setState({
keycode: CurrentKeyCode,
keyval: e.target.value
});
};
changeHandler = e => {
const CurrentValue = e.target.value;
console.log("changehandler ", CurrentValue);
const Digit_Regex = /^\d{0,4}$/;
const digitValidator = (oldValue, CurrentValue) => {
const inputFormattedValue = Digit_Regex.test(CurrentValue)
? CurrentValue
: oldValue;
return inputFormattedValue;
};
this.setState(prevState => ({
inputValue: digitValidator(prevState.inputValue, CurrentValue)
}));
};
render() {
return (
<div>
<label>Enter 4 digit Number</label>
<input
onKeyUp={e => this.state.addKeyUp && this.keyEventHandler(e)}
onChange={e => this.changeHandler(e)}
value={this.state.inputValue}
type="tel"
/>
{this.state.keycode && (
<p>
Keycode is {this.state.keycode} and val is {this.state.keyval}
</p>
)}
</div>
);
}
}
ReactDOM.render(<Input />, document.getElementById('root'))
View Compiled