React · Lesson 32 of 120
Passing Functions Down
Child to parent.
Props flow down. But what if a child needs to tell its parent something? The parent passes a function down, and the child calls it.
- Props flow down
- Child needs to talk
- Pass a function
Cards that add to a basket
The basket total lives in App. App passes an add function down to each card, as the on add prop. The card calls it when its button is clicked. So the child tells the parent something happened. We add a helmet, and two sets of lights. Run it.
App.jsxjsx
import { useState } from "react";
function ProductCard({ name, price, onAdd }) {
return (
<div className="box">
<b>{name}</b> £{price} <button id={"add" + price} onClick={() => onAdd(price)}>Add</button>
</div>
);
}
export default function App() {
const [total, setTotal] = useState(0);
const add = price => setTotal(t => t + price);
return (
<div>
<h2>Basket: £{total}</h2>
<ProductCard name="Helmet" price={40} onAdd={add} />
<ProductCard name="Lights" price={25} onAdd={add} />
</div>
);
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"click": "#add40"}, {"click": "#add25", "times": 2}]Naming
Props that take functions usually start with on, like on add, or on change. The functions you pass often start with handle. Data flows down as props. Events flow up through these functions.
| key | value |
|---|---|
| Prop name | onAdd, onChange |
| Function name | handleAdd |
| Data | flows down |
| Events | flow up |
Summary
Pass functions down, so children can tell parents what happened. Next, the state quiz.
Key takeaways- onAdd={add}
- Child calls it
- Parent updates
Next up: State Quiz — test yourself