1.0.1 • Published 5 years ago
react-hook-usenumberinput v1.0.1
react-hook-useNumberInput
React hook to handle using an input as numeric input
- Handles input from
<input>
- Maintains typed string value
- Provides valid real number
const [ value, real, valid, handleChange ] = useNumberInput(defaultValue, { min, max });
Params:
- defaultValue: starting input value, Can be string or Number
- options
- min: minimum value for bounds checking
- max: maximum value for bounds checking
Values:
- value: input field value
- real: value as a valid number
- valid: true if input can be parsed as a number and is within min/max bounds
- handleChange: call to update value
Converting input to real number:
import useNumberInput from 'react-hook-usenumberinput';
const NumberInput = props => {
const { defaultValue = 0 } = props;
const [value, real, , handleChange] = useNumberInput(defaultValue);
return (
<div>
<input id="input" onChange={e => handleChange(e.target.value)} value={value} />
<div id="output">{`${typeof real} ${real}`}</div>
</div>
);
};
With optional minimum and maximum:
import useNumberInput from 'react-hook-usenumberinput';
const NumberInput = props => {
const { defaultValue = 0, min, max } = props;
const [value, real, valid, handleChange] = useNumberInput(defaultValue, { min, max });
return (
<div>
<input id="input" onChange={e => handleChange(e.target.value)} value={value} />
<div id="output">{`${typeof real} ${real}`}</div>
<div id="valid">{`${valid ? 'valid' : 'invalid'}`}</div>
</div>
);
};