Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Components

A component is a function that returns JSX. It describes one piece of the interface: a header, a list item, a button. By splitting a page into components you get small files that are easy to read and reuse.

A component in its own file

Each component usually lives in its own file in src/components/. Create the folder and the file src/components/Header.jsx:

// src/components/Header.jsx
export default function Header() {
  return (
    <header>
      <h1>My tasks</h1>
    </header>
  );
}

The file name matches the component name. export default makes the function available to other files.

Using it

To render a component, import it and write it as a tag:

// src/App.jsx
import Header from './components/Header.jsx';
 
export default function App() {
  return (
    <div>
      <Header />
      <p>No tasks yet.</p>
    </div>
  );
}

React calls the Header function and puts its markup in place of the tag. The page at http://localhost:5173 shows the heading with a paragraph below it.

Reuse

One component can be rendered as many times as you like. Create src/components/TodoItem.jsx:

// src/components/TodoItem.jsx
export default function TodoItem() {
  return <li>New task</li>;
}
// src/App.jsx
import Header from './components/Header.jsx';
import TodoItem from './components/TodoItem.jsx';
 
export default function App() {
  return (
    <div>
      <Header />
      <ul>
        <TodoItem />
        <TodoItem />
        <TodoItem />
      </ul>
    </div>
  );
}

The page shows a list of three identical items. To make the items differ, the component is given data — that is the next lesson.

The component tree

Components nest inside each other and form a tree. App is at the top, its children below:

App
├── Header
└── ul
    ├── TodoItem
    ├── TodoItem
    └── TodoItem

You can see this tree in the React Developer Tools browser extension — it helps you understand what a page is built from.

Rules

RuleExample
The name starts with a capital letterTodoItem, not todoItem
One root element is returnedA div or a fragment
Components are declared at the top level of a fileNot inside another component

Common mistake

A component name must start with a capital letter. React treats a lowercase tag as a plain HTML tag:

function header() {
  return <h1>My tasks</h1>;
}
 
// <header /> renders an empty HTML header tag, not your component.
// Correct: function Header() and <Header />

There is no error — the page simply shows nothing, which makes this hard to notice.

Thanks for reading!

Donate to the site — we work hard for you.