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 }), adivwith the classfruitshowingNAME: COUNTin aspanand abuttonAdd NAME. Appkeeps both counts, renders counters forApplesandOranges, and apwith the idtotalshowingTotal: 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>
);
}