What you'll learn
How to write a component, how to use it inside another one, and why splitting a page into components helps.
Why it matters
Big interfaces are built from many small parts: a button, a card, a menu. Components let you build each part once and reuse it everywhere.
Explanation
A component is a JavaScript function that returns JSX. Its name must start with a capital letter, which is how React tells it apart from a normal HTML tag.
You use a component like a custom HTML tag:
function Greeting() {
return <h2>Welcome back</h2>;
}
function App() {
return (
<div>
<Greeting />
<Greeting />
</div>
);
}Each <Greeting /> is a separate copy. Components can contain other components, which gives you a tree of pieces.
Example
function Header() {
return <h1>My Shop</h1>;
}
function Product() {
return (
<div style={{ border: "1px solid #ccc", padding: 12, margin: "8px 0" }}>
<strong>Notebook</strong> - 40 rupees
</div>
);
}
function App() {
return (
<div style={{ fontFamily: "system-ui" }}>
<Header />
<Product />
<Product />
</div>
);
}Step-by-step walkthrough
HeaderandProductare small components, each returning a piece of UI.Appis the top-level component. It uses the others as tags.- React calls each component function and puts the JSX it returns on the page.
Productappears twice, so you get two cards from a single definition.- Right now both cards show the same thing. In the next lesson, props make each one different.
Try it yourself
Add a Footer component that shows "Thanks for visiting" and place it at the bottom of App.
Common mistakes
- Lower-case component names.
<product />is treated as an HTML tag. - Forgetting to return JSX from the function.
- Defining a component inside another component, which makes React rebuild it on every render.
- Calling it like a function (
Product()) instead of using it as a tag.
Quick quiz
Summary
- A component is a function returning JSX, named with a capital letter.
- Use components as tags and nest them in a tree.
- Reuse beats copy-paste.
Next: giving each component different data with props.