react-typed-inputs v2.0.4
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';
function Form() {
const [value, setValue] = useState(42);
return (
<input
type="number"
value={value}
onChange={(event) => setValue(Number(event.currentTarget.value))}
/>
);
}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
onValueChangeinstead ofonChange. (Behavior of the latter is kept intact in all cases.) - Controlled components accept
nullas 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';
function Form() {
const [value, setValue] = useState(42);
return <NumericInput value={value} onValueChange={setValue} />;
}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": Whenstepis an integer, which is true unless overrided."decimal": Whenstepis 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 adjustingvaluewhen the component loses focus.roundAfterBlur: Enforcesstepconstraint by adjustingvaluewhen the component loses focus.