Last active
November 26, 2019 15:28
-
-
Save nathansmith/11a98dfc242d3aa8094cd11f63b2eff9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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