react-typed-inputs
Strongly typed input components for React.
💡 Motivation
HTML form elements keep their internal state as strings. While the variable below retains its numeric type, it cannot be cleared by the user.
import useState from 'react'; { const value setValue = ; return <input ="number" = = /> ;}
This happens because the empty input value gets converted to 0
by Number('')
. Checking for edge cases would make the code difficult to reason about.
New issues arise when introducing null
for intentionally missing values (in place of ''
or NaN
). Although a special valueAsNumber
attribute exists, it does not support the culture-independent decimal point (.
) in all browsers.
A live demo is available for demonstrating the differences between prior approaches.
📚 Usage
Import one of the components as documented below.
- Use
onValueChange
instead ofonChange
. (Behavior of the latter is kept intact in all cases.) - Controlled components accept
null
as theirvalue
, denoting an empty field. - Uncontrolled components support all the described behavioral additions.
Enjoy the benefits of type annotations and tree shaking out of the box.
<NumericInput>
import useState from 'react';import NumericInput from 'react-typed-inputs'; { const value setValue = ; return <NumericInput = = />;}
Props
Overridable defaults
type
: Equals"text"
.- Using
"number"
is not recommended. - Typing a decimal point doesn’t nullify the value by default.
- Using
inputMode
: Set to one of the following only whenmin >= 0
, as devices may not show a minus key (-
)."numeric"
: Whenstep
is an integer, which is true unless overrided."decimal"
: Whenstep
is not an integer.
pattern
: Serves as a fallback for setting input mode in iOS Safari.
Opt-in behavior
clampAfterBlur
: Enforces range constraints (min
,max
) by adjustingvalue
when the component loses focus.roundAfterBlur
: Enforcesstep
constraint by adjustingvalue
when the component loses focus.