React: Two units, one source of truth

Two inputs that must always agree are the classic case for one source of truth.

What to build

Kilometre and mile fields that convert into each other as you type.

Requirements

  • Write DistanceInput({ id, label, value, onChange }) rendering a label with the text and a controlled input with that id; the two inputs have the ids km and miles.
  • App stores only what was last typed and in which unit. The other field shows the converted value (1 mile = 1.609344 km) rounded to two decimals, without trailing zeros (for example 6.21, 16.09, 5). An empty field leaves the other empty.
  • Below them, a p with the id note says That is a long walk when the distance is at least 10 km, and An easy walk otherwise (nothing when empty).

Constraints

Do not store both values in state.

Example

Typing 10 in kilometres shows 6.21 in miles and "That is a long walk"; typing 1 in miles shows 1.61 in kilometres and "An easy walk".

Why it works

Only one value is stored, so the two fields cannot disagree; each render converts it into the other unit and works out the note from the same number.

Hints

Hint 1

Store the text the user typed and which field it was typed in: { unit: "km", text: "10" }.

Hint 2

The other field shows the conversion, rounded to two decimals: String(Math.round(x * 100) / 100).

Solution

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

const KM_PER_MILE = 1.609344;
const round = (x) => String(Math.round(x * 100) / 100);

function DistanceInput({ id, label, value, onChange }) {
  return (
    <label>
      {label} <input id={id} value={value} onChange={(e) => onChange(e.target.value)} />
    </label>
  );
}

export default function App() {
  const [typed, setTyped] = useState({ unit: "km", text: "" });
  const empty = typed.text === "";
  const kmNumber = typed.unit === "km" ? Number(typed.text) : Number(typed.text) * KM_PER_MILE;
  const km = typed.unit === "km" ? typed.text : empty ? "" : round(kmNumber);
  const miles = typed.unit === "miles" ? typed.text : empty ? "" : round(kmNumber / KM_PER_MILE);

  return (
    <div>
      <DistanceInput id="km" label="Kilometres" value={km} onChange={(text) => setTyped({ unit: "km", text })} />
      <DistanceInput id="miles" label="Miles" value={miles} onChange={(text) => setTyped({ unit: "miles", text })} />
      <p id="note">{empty ? "" : kmNumber >= 10 ? "That is a long walk" : "An easy walk"}</p>
    </div>
  );
}

Lesson: Sharing state between components →