0

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.

Vmxes
  • 2,329
  • 2
  • 19
  • 34
  • change type="number" – devd Aug 11 '20 at 15:34
  • As the question was mistakenly closed, I write the solution here. The problem was that value was not present in the props so the component become uncontrolled. This post helped me: [link](https://stackoverflow.com/questions/34006333/cant-type-in-react-input-text-field) – Vmxes Aug 16 '20 at 10:35

1 Answers1

0

Ciao try to modify your input type like this:

    <input name = {props.name}
           id = {props.name + '-id'}
           type = "number"
           className = {props.className}
           maxLength = {maxLength}
           value = {intValue}
           onChange = {handleChange}
    />

This should solve your problem.

Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30