I am trying to do a simple input form which only accepts numbers with a total length of 10 characters.
I am using the maxLength attribute in my JSX to limit input length:
<FormControl input type="tel" maxLength="10" onKeyDown={(e)=> checkInput(e)} />
And here is the function where I check if the key is allowed (digits and backspace keys only)
const [number, setNumber] = useState()
const checkInput = (e) =>{
if(!(e.keyCode >= 48 && e.keyCode <= 57 || e.keyCode === 8)){
e.preventDefault()
}
else{
setNumber(e.target.value)
}
}
This works fine except for the state which is always one keystroke behind due to the keyDown e.listener.
I also tried using the type="number"
attribute in my JSX but this does not work in conjunction with max=9999999999
neither with maxLength=10
attributes
CodePudding user response:
Properly duplicate: e.target.value shows values one key 'behind'
Solution with onChange:
import React from "react";
import { useState } from "react";
import { FormControl } from "react-bootstrap";
const App = () => {
const [number, setNumber] = useState("");
const checkInput = (e) => {
const onlyDigits = e.target.value.replace(/\D/g, "");
setNumber(onlyDigits);
};
console.log({ number });
return (
<div>
<FormControl
type="tel"
maxLength="10"
value={number}
onChange={(e) => checkInput(e)}
/>
</div>
);
};
export default App;