React: A tip calculator

A calculator is a form whose results are derived from its fields as the user types.

What to build

A tip calculator that splits a bill.

Requirements

  • Controlled fields: an input with the id bill (type number), a select with the id tip with the options 10, 15 and 20 (percent; 15 to start), and an input with the id people (type number, 1 to start).
  • While typing, show the results in a div with the id result: Tip: T, Total: S and Each: E as three p elements, all with two decimals.
  • If the bill is empty or negative, the result shows only Enter the bill; otherwise, if people is less than 1 or not a whole number, it shows only At least one person.

Constraints

Compute the results during render; do not store them in state.

Example

A bill of 60 with 15% for 4 people shows "Tip: 9.00", "Total: 69.00" and "Each: 17.25".

Why it works

Only what the user typed is state; the tip, total and share are worked out from it on every render, so they can never be out of date.

Hints

Hint 1

Keep the three fields' text in state, and compute the numbers and results during render.

Hint 2

Check the inputs in order and show one message instead of the results when something is wrong.

Solution

Show one correct solution (try it yourself first)
import { useState } from "react";

export default function App() {
  const [bill, setBill] = useState("");
  const [tip, setTip] = useState("15");
  const [people, setPeople] = useState("1");

  const amount = Number(bill);
  const count = Number(people);
  let result;
  if (bill === "" || amount < 0) {
    result = <p>Enter the bill</p>;
  } else if (!Number.isInteger(count) || count < 1) {
    result = <p>At least one person</p>;
  } else {
    const tipAmount = (amount * Number(tip)) / 100;
    const total = amount + tipAmount;
    result = (
      <>
        <p>Tip: {tipAmount.toFixed(2)}</p>
        <p>Total: {total.toFixed(2)}</p>
        <p>Each: {(total / count).toFixed(2)}</p>
      </>
    );
  }

  return (
    <div>
      <input id="bill" type="number" value={bill} onChange={(e) => setBill(e.target.value)} />
      <select id="tip" value={tip} onChange={(e) => setTip(e.target.value)}>
        <option value="10">10</option>
        <option value="15">15</option>
        <option value="20">20</option>
      </select>
      <input id="people" type="number" value={people} onChange={(e) => setPeople(e.target.value)} />
      <div id="result">{result}</div>
    </div>
  );
}

Lesson: Forms and controlled inputs →