Home / Learn React / Components: The Building Blocks

Components: The Building Blocks

A component is a JavaScript function that returns JSX. You build a page by putting components inside other components, like building with blocks.

In shortA component is a function whose name starts with a capital letter and that returns JSX. Use it like an HTML tag.

Theory in plain words

A page is a tree of componentsLogoMenuHeaderProductCardProductCardProductListCartMainFooterApp
A page is a tree of components

What it is

A component is a reusable piece of UI. In modern React it is a plain function. It can use other components inside its JSX, so a whole app is a tree of components.

Why we use it

Components let you write something once and use it many times, test it alone, and change it in one place. Big screens become small, easy to understand pieces.

How it works

React calls your function and uses the JSX it returns. A capital letter tells React that <Card /> is your component and not an HTML tag such as <div>. Each use of <Card /> gets its own props and its own state.

Where it is used

  • Buttons, cards, navbars, modals and forms
  • Whole pages and layouts
  • List items such as products, comments and messages
  • Anything you want to reuse

Write and use a component

Your first componentTry it Yourself

Add a third <Welcome /> and run again.

Naming rules

Split a screen into componentsTry it Yourself

Components with different looks: props

Two copies of the same component usually show different data. That data arrives through props. You will learn them in the next lesson.

Files and exports

Card.jsx and App.jsx
// Card.jsx
export default function Card() {
  return <div className="card">Hello</div>;
}

// App.jsx
import Card from "./Card.jsx";

export default function App() {
  return <Card />;
}

In a real project each component usually has its own file. export default lets you import it with any name. A named export (export function Card) must be imported with braces: import { Card } from "./Card.jsx".

Tip:Class components (class X extends React.Component) still work but new code uses function components and hooks. The only thing that still needs a class is an old style error boundary.
Careful:Do not call a component like a function: write <Card />, not Card(). Calling it directly breaks hooks and state.

Quick quiz

1. A component name must start with...

2. How should you use a component?

3. Why not define a component inside another component?

Common questions

How should you use a component?

<Card />. Use it like a tag. Calling it as a function breaks hooks.

Why not define a component inside another component?

It is recreated every render and loses its state. A new function identity each render makes React treat it as a different component.