A callback is a function passed through props so another component can invoke it later, usually after a user event. This lets a rendered component report selections, submit orders, or request filtering without owning the surrounding application logic. section 16.8.1 section 17.3.1
Type the callback according to the data the component must send:
- Use a parameterless callback for an action such as submitting an order: submitCallback: () => void. section 17.3.1
- Pass data with the callback when the parent needs the user's choice: callback: (selected: string) => void. section 16.8.1
- Invoke the callback from JSX event props, often through an arrow function when arguments must be supplied: onclick={() => this.props.callback(cat)}. section 16.8.1
- Use arrow-function event handlers when the handler needs the component's this value; conventional methods can receive a different this when passed as callbacks. section 16.8.1 section 3.6.2
Filtering and submitting
A product list can pass filterCallback to CategoryList, whose buttons invoke it with a category. A header can expose submitCallback to a button, which invokes it without arguments. The callback signatures make both communication paths explicit. section 16.8.1 section 17.3.1
Listing 16.32 The contents of the categoryList.tsx file in the src folder
import { createElement } from "./tools/jsxFactory";
export class CategoryList {
props: {
categories: string[];
selectedCategory: string,
callback: (selected: string) => void
}
getContent(): HTMLElement {
return <div className="d-grid gap-2">
{ ["All", ...this.props.categories]
.map(c => this.getCategoryButton(c))}
</div>
}
getCategoryButton(cat?: string): HTMLElement {
let selected = this.props.selectedCategory === undefined
? "All": this.props.selectedCategory;
let btnClass = selected === cat ? "btn-primary": "btn-secondary";
return <button className={ `btn btn-block ${btnClass}` }
onclick={ () => this.props.callback(cat)}>
{ cat }
</button>
}
}
Inspect the complete CategoryList implementation, including its callback type and the button handler that supplies the selected category. section 16.8.1
Listing 17.10 The contents of the header.tsx file in the src folder
import { createElement } from "./tools/jsxFactory";
import { Order } from "./data/entities";
export class Header {
props: {
order: Order,
submitCallback: () => void
}
getContent(): HTMLElement {
let count = this.props.order.productCount;
return <div className="p-1 bg-secondary text-white text-end">
{ count === 0 ? "(No Selection)"
: `${ count } product(s), $`
+ `${ this.props.order.total.toFixed(2)}` }
<button className="btn btn-sm btn-primary m-1"
onclick={ this.props.submitCallback }>
Submit Order
</button>
</div>
}
}
Inspect a parameterless callback used by a header button to submit an order. section 17.3.1


















