Sub topic 3
Building UIs from components
This chapter assumes you know JavaScript functions, objects and ES modules, and basic HTML. JSX and props get a fuller treatment in later chapters. Here you only need to read them well enough to follow the examples.
What a component is
A component is a reusable piece of UI. In modern React, a component is a JavaScript function that returns a description of what should appear on screen. React calls that function, takes the result, and updates the page to match.
Two rules cover most of the common errors:
- A component name must start with a capital letter. React treats
<counter />as an HTML tag and<Counter />as your component. - A component returns one root element. Wrap siblings in a parent element or a fragment (
<>...</>).
A first component
function Greeting() {
return <p>Hello from a component</p>
}
export default GreetingThe export default line lets other files import the component. Each component usually lives in its own file, named after the component.
Composing components
You build a screen by nesting components inside each other, the same way you nest HTML elements. A component that uses another one is its parent. The one it uses is its child.
import Greeting from './Greeting.jsx'
function App() {
return (
<main>
<h1>My first React app</h1>
<Greeting />
<Greeting />
</main>
)
}
export default AppGreeting is used twice here. Each use creates an independent instance, so you write the markup once and reuse it.
React keeps this tree in memory. When data changes, it re-runs the affected component functions and updates only the parts of the page that differ.
Why split into components
Splitting a UI has practical benefits:
- You reuse markup and behavior instead of copying it.
- You can read, test and change one piece without touching the rest.
- A component can hold its own state, so a change stays local to it.
A common guideline is to extract a component when a piece of markup repeats, or when a function grows hard to read. Don't split earlier than that.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Lowercase component name | Nothing renders, or the browser warns about an unknown tag | Rename it to `Greeting` |
| Calling a component as a function, `Greeting()` | Hooks break and state is lost | Write `<Greeting />` |
| Defining a component inside another component | State resets on every render | Move it to the top level of the file |
| Forgetting `export default` | Import error such as "does not provide an export named default" | Add the export |
Where components start
In a Vite project, src/main.jsx renders App into the #root element. Everything else you build hangs below App as children.
Exercise
Why does <greeting /> fail to show your Greeting component, and how do you fix it?
Show answer
React treats lowercase tags as built-in HTML elements, so it looks for an HTML element named greeting and finds none. Capitalize the name and write <Greeting />, making sure the component is imported.