React
by Faisal Khan Janjua
HTML
<div id="app"></div>
SCSS
body {
margin: 0;
text-align: center;
}
.pinFields {
margin: 0 -6px;
margin-top: 16px;
&:after {
clear: both;
content: '';
display: table;
}
& .pinField {
width: 20%;
float: left;
padding: 0 6px;
& input {
width: 100%;
border: none;
font-size: 36px;
font-weight: 300;
padding-bottom: 0;
text-align: center;
outline: none !important;
border-bottom: 2px solid #333;
}
}
}
React
class PinFields extends React.Component {
constructor(props) {
super(props)
this.state = {
otp: {},
pin: ''
}
}
preventChar = (e) => {
if (e.key === 'E' || e.key === 'e' || e.key === '.' || e.key === '-' || e.key === '+') { e.preventDefault(); }
}
handleFocus = e => {
let field = e.target.name;
let lastChar = parseInt(field.charAt(field.length - 1));
if (e.keyCode > 47 && e.keyCode < 58) {
if (lastChar < 3) {
field = field.replace(lastChar, lastChar + 1);
this.refs[field].focus();
}
}
if (e.keyCode === 8) {
if (lastChar <= 3 && lastChar >= 1) {
field = field.replace(lastChar, lastChar - 1);
this.refs[field].focus();
}
}
/* let num = e.target.value;
num.replace(/\D/g,"");
if(num) {
console.log(num); */
const that = this;
/* let otp = { ...this.state.otp };
otp[e.target.name] = parseInt(e.target.value);
this.setState({ otp }, function(){
console.log(that.state.otp);
}); */
let refs = this.refs, value = "";
for (let key in refs) {
if (refs.hasOwnProperty(key)) {
value += refs[key].value;
// console.log(value);
}
}
let pin = {...this.state.pin}
if(value.length === 4) {
pin = value;
this.setState({pin}, function(){
console.log(that.state.pin);
});
}
else {
pin = '';
this.setState({pin}, function(){
console.log(that.state.pin);
});
}
/* } */
}
render() {
return (
<div className="pinFields">
<div className="pinField">
<input name="otp0" min="0" max="9" ref="otp0" onPaste={e => e.preventDefault()} onKeyUp={this.handleFocus} onKeyDown={this.preventChar} onChange={this.mxLn} type="number" className="noArrows" />
</div>
<div className="pinField">
<input name="otp1" min="0" max="9" ref="otp1" onPaste={e => e.preventDefault()}...