Search code examples
reactjsreact-proptypes

ReactJS - number only input with PropType set to number but gets initialized to zero


I'm using ReactJS and creating a basic controlled text input box that I want to only allow numbers. It is controlled so the value is the state variable and onChange updates the state. I also have the PropType set to a number. But when I do that, I have to initialize the state variable to zero and then the input box gets prefilled with zero. Obviously this is not very friendly to the user. Wondering if anyone knows of a way around this. If not, I will just have to change the PropType to a string and be OK with that. I did find a very similar question and answer, but it is specific to Angular: AngularJS <input> with type set to 'number', how to force a initial display of value to a non-number string

Relevant code:

State: const [lastPalletBagCount, setLastPalletBagCount] = useState(0);

Input:

<input
    type={'text'}
    className={'bag-count'}
    value={lastPalletBagCount}
    onChange={(e) =>
        setLastPalletBagCount(e.target.value)
    }
/>

Proptype: lastPalletBagCount: PropTypes.number.isRequired,


Solution

  • You can do:

    Comp.propTypes = {
      lastPalletBagCount: PropTypes.oneOfType([
        PropTypes.number,
        PropTypes.oneOf([''])
      ]).isRequired
    }