Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Last active November 26, 2019 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathansmith/11a98dfc242d3aa8094cd11f63b2eff9 to your computer and use it in GitHub Desktop.
Save nathansmith/11a98dfc242d3aa8094cd11f63b2eff9 to your computer and use it in GitHub Desktop.
import React from 'react'
import PropTypes from 'prop-types'
const InputNumber = (props = {}) => {
const {
handleChange = () => {},
...otherProps
} = props
const onKeyDown = (e = {}) => {
const {
ctrlKey,
metaKey,
key = '',
target = {}
} = e
const { type } = target
if (
!ctrlKey &&
!metaKey &&
type === 'number' &&
key.length === 1 &&
(/[^0-9.]/g).test(key)
) {
e.preventDefault()
}
}
const onChange = (e = {}) => {
const { target = {} } = e
const {
maxLength,
name,
value = ''
} = target
let newValue = value
if (
newValue &&
maxLength &&
newValue.length > maxLength
) {
newValue = newValue.slice(0, maxLength)
target.value = newValue
}
handleChange(name, newValue)
}
return (
<input
{...otherProps}
type='number'
onKeyDown={onKeyDown}
onChange={onChange}
/>
)
}
InputNumber.propTypes = {
handleChange: PropTypes.func
}
export default InputNumber
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment