A React component is a reusable interface unit defined as a class or function. It uses JSX to render HTML-like content, receives data or callbacks through props, and can manage changing values with state and hooks. section 20.6 section 20.4.3
Use components to divide an application into focused, composable interface units:
- Define a function or class whose name identifies the component. section 20.0
- Render the component with a custom HTML-like element whose tag matches its name. section 20.4.3
- Pass data and callback functions through props. section 20.4.3
- Use state and hooks when interaction changes what the component displays. section 20.4.3
- Compose larger interfaces from smaller components such as headers, category lists, and product items. section 20.4.3
A typed function component
A ProductList component declares a Props interface, receives products, categories, selections, and an addToOrder callback, then filters products using local selectedCategory state before rendering Header and other child components. App renders ProductList with test data and manages selections with useState. section 20.4.3
Listing 20.15 The contents of the productList.tsx file in the src folder
import React, { FunctionComponent, useState } from "react";
import { Header } from "./header";
import { ProductItem } from "./productItem";
import { CategoryList} from "./categoryList";
import { Product, ProductSelection } from "./data/entities";
interface Props {
products: Product[],
categories: string[],
selections: ProductSelection[],
addToOrder: (product: Product, quantity: number) => void
}
export const ProductList: FunctionComponent<Props> = (props) => {
const [selectedCategory, setSelectedCategory] = useState("All");
const products = props.products.filter(p => selectedCategory === "All"
|| p.category === selectedCategory);
return <div>
<Header selections={ props.selections } />
<div className="container-fluid">
<div className="row">
<div className="col-3 p-2">
<CategoryList categories={ props.categories }
selected={ selectedCategory }
selectCategory={ setSelectedCategory } />
</div>
<div className="col-9 p-2">
{
products.map(p =>
<ProductItem key={ p.id } product={ p }
callback={ props.addToOrder } />)
}
</div>
</div>
</div>
</div>
}
View the complete productList.tsx listing, including its Props interface, useState call, filtering logic, child components, and JSX structure. section 20.4.3
Components also participate in application navigation. Routing can select which component appears for the current URL, while route hooks provide parameters used by components such as an order confirmation view. section 21.3 section 21.3.1
