Composing components
The power of components is nesting them. You build small pieces, then assemble bigger pieces out of them, exactly like functions calling functions in Advanced JavaScript:
function Header() { return <header><h1>Task Tracker</h1></header>; } function TaskItem() { return <li>Water the plants</li>; } function App() { return ( <div> <Header /> <ul> <TaskItem /> <TaskItem /> </ul> </div> ); }
When React renders <App />, it calls App, sees <Header /> and <TaskItem /> inside, and calls those too, all the way down until only real tags remain. The result is a component tree.
Small components, assembled
Good React code reads like an outline. App tells you the page has a header and a list, and each child component handles its own details. Compare that with one giant function containing every tag on the page.
The same idea works in plain JavaScript with our string-returning functions from lesson 1-2. Composition is just functions calling functions, JSX only makes it look like markup.
Code exercise · javascript
Your turn. Complete card(title, body) so it returns "<section><h2>TITLE</h2><p>BODY</p></section>", then complete page() so it composes header("Dashboard") followed by two cards: Weather with body Sunny, and Inbox with body 3 new.
Quiz
In the App example above, what does React do when it encounters <TaskItem /> while rendering?