React: Counters that share a total

Two counters and a total that adds them up: lift the counts into the parent so the total can see them.

What to build

Two fruit counters with a shared total.

Requirements

  • Write FruitCounter({ name, count, onAdd }), a div with the class fruit showing NAME: COUNT in a span and a button Add NAME.
  • App keeps both counts, renders counters for Apples and Oranges, and a p with the id total showing Total: N.

Constraints

FruitCounter must not have its own state.

Example

Adding two apples and one orange shows "Apples: 2", "Oranges: 1" and "Total: 3".

Why it works

Because the counts live in App, it can add them up for the total, and the counters only show what they are given and report clicks.

Hints

Hint 1

Keep both counts in App, for example as an object { apples: 0, oranges: 0 }.

Hint 2

FruitCounter receives its count and an onAdd callback as props.

Solution

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

function FruitCounter({ name, count, onAdd }) {
  return (
    <div className="fruit">
      <span>
        {name}: {count}
      </span>
      <button onClick={onAdd}>Add {name}</button>
    </div>
  );
}

export default function App() {
  const [counts, setCounts] = useState({ apples: 0, oranges: 0 });
  return (
    <div>
      <FruitCounter name="Apples" count={counts.apples} onAdd={() => setCounts({ ...counts, apples: counts.apples + 1 })} />
      <FruitCounter name="Oranges" count={counts.oranges} onAdd={() => setCounts({ ...counts, oranges: counts.oranges + 1 })} />
      <p id="total">Total: {counts.apples + counts.oranges}</p>
    </div>
  );
}

Lesson: Sharing state between components →