File size: 1,238 Bytes
74aacd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import React, {
  FormEvent,
  InputHTMLAttributes,
  useEffect,
  useState,
} from 'react'
import TextInput from './Input'

interface NumberInputProps extends InputHTMLAttributes<HTMLInputElement> {
  value: string
  allowFloat?: boolean
  onValue?: (val: string) => void
}

const NumberInput = React.forwardRef<HTMLInputElement, NumberInputProps>(
  (props: NumberInputProps, forwardedRef) => {
    const { value, allowFloat, onValue, ...itemProps } = props
    const [innerValue, setInnerValue] = useState(value)

    useEffect(() => {
      setInnerValue(value)
    }, [value])

    const handleOnInput = (evt: FormEvent<HTMLInputElement>) => {
      const target = evt.target as HTMLInputElement
      let val = target.value
      if (allowFloat) {
        val = val.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1')
        onValue?.(val)
      } else {
        val = val.replace(/\D/g, '')
        onValue?.(val)
      }
      setInnerValue(val)
    }

    return (
      <TextInput
        value={innerValue}
        onInput={handleOnInput}
        className="number-input"
        {...itemProps}
        ref={forwardedRef}
      />
    )
  }
)

NumberInput.defaultProps = {
  allowFloat: false,
}

export default NumberInput