Function Components
Look at any web page and you can see boxes inside boxes: a header, a list, each item in the list, a button inside each item. React asks you to name those boxes and write each one once. Each named box is a component.
The rule
A component is a capitalised function that returns markup.
Three parts to that rule:
- A function. Nothing more exotic than a normal JavaScript function.
- Capitalised.
BookCard, notbookCard. JSX uses the first letter to decide: lowercase means a built-in HTML tag, capital means your component. - Returns markup. It returns JSX, which describes what should appear. It may return
nullto show nothing.
Here is the first piece of the reading-list app this course builds:
function BookCard() {
return (
<article className="book">
<h2>The Hobbit</h2>
<p>J. R. R. Tolkien</p>
</article>
);
}
export default function App() {
return (
<main>
<h1>My reading list</h1>
<BookCard />
<BookCard />
</main>
);
}App uses BookCard twice, like an HTML tag. Each use creates a separate instance on the page. Wrapping a multi-line return in parentheses avoids a classic JavaScript trap where a bare return on its own line returns nothing.
Define components at the top level of a file, never inside another component. A component defined inside another is recreated on every render, which resets its state and slows things down.
Older code uses class BookCard extends React.Component. Those still work, but modern React is written with functions and hooks, and that is what this course uses.
The shortcut
Draw boxes, then name them. Any box that repeats, or that has a clear job, becomes a component.
Draw the outer box
The whole page is
App. It holds everything else.
If a component grows past one screen, draw smaller boxes inside it. Small components are easier to read, test and reuse.
Drills
Answer fast — trust the rule.
Which of these can be used as <X /> to render your own component?
What does JSX do with <header /> written in lowercase?
A component should render nothing when there is no data. What can it return?
Why should BookCard not be defined inside App's function body?
Remember
- A component is a capitalised function that returns markup (or
null). - Draw boxes; anything that repeats or has a clear job becomes a component.
- Trap: lowercase names and components defined inside other components.
