Numbers from Fields

A field for numbers is an input with type="number". The user types a number into it, or clicks its little arrows. In React, it's controlled like any other field, and you know from the JavaScript course what its value is: text. Even when the field shows 3, event.target.value is "3".

Keep the text in the state, as the field gives it, and turn it into a number with Number() where you calculate with it:

import { useState } from "react";

export default function App() {
    const [tokens, setTokens] = useState("1");
    const total = Number(tokens) * 3;

    return (
        <main>
            <label htmlFor="tokens">Drink tokens, €3 each</label>
            <input
                id="tokens"
                type="number"
                value={tokens}
                onChange={(event) => setTokens(event.target.value)}
            />
            <p>To pay: €{total}</p>
        </main>
    );
}

Why not a number in the state, with setTokens(Number(event.target.value))? Because of the moment when the field is empty, as when the user deletes the 1 to type a 4. Number("") is 0, so the state would be 0, and the field would show 0 right away. With text in the state, the field shows exactly what the user typed, and only the calculation sees a number. There, an empty field counts as 0.

And why Number() at all? * turns text into a number by itself, so "3" * 3 happens to be 9. But + doesn't: "3" + 1 is "31". With Number(), you don't have to remember which is which.

Instructions

Make the quantity field controlled with a state variable quantity that starts as "1", and show the quantity in ticket-quantity, for example Tickets: 3.

Show the total in total: the quantity times the price of the chosen ticket, for example Total: €135 for 3 Saturday tickets.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

5/9

Next