Splitting the Page
So far, the whole festival page was in App. That's fine for a heading and a paragraph. But a real app has a header, a lineup, tickets, a footer… and App would soon grow to hundreds of lines in which nothing is easy to find.
That's why React apps split the page into components, one for each part. You already know how to write one: a function whose name starts with a capital letter and that returns JSX. Here's the header of the festival page as a component of its own:
function Header() {
return (
<header>
<h1>Summer Sounds</h1>
<p>Friday and Saturday, three stages</p>
</header>
);
}
export default function App() {
return (
<>
<Header />
<Lineup />
</>
);
}Header returns its part of the page, and App puts the parts together: <Header /> means "call the function Header and put what it returns here". The page looks exactly the same as before. But App now reads like a table of contents: the header, then the lineup. When you want to change the header, you know where to look. (Lineup is written the same way, and in this exercise, you'll write it.)
A few rules you already know:
- The name starts with a capital letter:
Header, notheader.<header>with a small h is the HTML element,<Header />with a capital H is your component. - A component with nothing between its tags is written as one self-closing tag:
<Header />. - A component returns one element, or a fragment
<>…</>, just likeApp.
How big should a component be? There's no exact rule. A good sign is that you can name it in a word or two: a header, a lineup, a band's card. When you'd need a long name to say what a component does, it's probably doing too much, and it can be split again.
Instructions
Move the <header> element, with everything in it, into a new component Header above App. In App, put <Header /> where the header was. Run the code: the page looks the same as before.
Do the same with the lineup: a component Lineup that returns the <section>. App then returns just <Header /> and <Lineup /> in a fragment.