I'm new to React and try to create a simple integer input field that allows only numbers to enter.
My code:
import React, {useState} from "react";
export const IntegerInput = props => {
const maxLength = props.maxLength ? parseInt(props.maxLength) : 10;
const [intValue, setIntValue] = useState(props.value);
const inputMask = new RegExp(/^[0-9\b]+$/);
function handleChange(e) {
let inputValue = e.target.value;
let isNumber = inputMask.test(inputValue);
let isEmpty = inputValue === '';
if (isEmpty || isNumber) {
console.log('Update value to: ' + inputValue);
setIntValue(inputValue);
} else {
console.log('Invalid input: ' + inputValue);
}
}
return (
<input name = {props.name}
id = {props.name + '-id'}
type = "text"
className = {props.className}
maxLength = {maxLength}
value = {intValue}
onChange = {handleChange}
/>
);
}
There is no error in the console and setIntValue
is called only if needed but still can enter any character in the input field.
What could be the problem?
Please note, that I want to use "text" input and not "number" and I have the problem on the React side and not with the JavaScript.