A number input looks like a text input, but its usual `value` is still a string. Read `evt.target.valueAsNumber` when you need the current entry as a number rather than parsing `evt.target.value` yourself. section 9.2.5
Read a number when the form submits
Give an uncontrolled input a name, then read it through the form’s `elements` collection: `const value = evt.target.elements.operand.valueAsNumber;`. In a natural-number sum calculator, the submit handler uses that number to calculate `(value * (value + 1)) / 2`. The input can start at `defaultValue="1"`; it does not need its own React state or a change handler. section 9.3
Listing 9.14 The sum of natural numbers
import { useState } from "react";
function NaturalSum() {
const [sum, setSum] = useState(0); #1
const onSubmit = (evt) => {
const value = #2
evt.target.elements.operand.valueAsNumber; #2
const naturalSum = (value * (value + 1)) / 2;
setSum(naturalSum);
evt.preventDefault();
};
return (
<form
onSubmit={onSubmit}
style={{ display: "flex", flexDirection: "column" }}
>
<label>
Number:
<input
type="number"
min="1"
defaultValue="1" #3
name="operand" #3
/>
</label>
<div>
<button>Submit</button>
</div>
<div>Sum: {sum}</div>
</form>
);
}
function App() {
return <NaturalSum />;
}
export default App;
The complete `NaturalSum` component shows the named number input, submit handler, and displayed sum together. section 9.3
The property also applies to `range` and calendar inputs. For most calendar input types, it returns a timestamp in milliseconds from January 1, 1970, rather than the formatted string returned by `value`. A `month` input is different: it returns the number of months since January 1970. Numeric inputs can also specify `min`, `max`, and `step`. section 9.2.5
Choose when to read the number based on the form. A controlled input keeps its value in component state as it changes; an uncontrolled input can leave the value in the DOM until submission. `valueAsNumber` works for the submit-time read, but an uncontrolled input is harder to change from the component after its initial value is set. section 9.2.5 section 9.3
