Skip to the workspace
Pebellslearn by building
Components and JSX  ›  Lesson

Function Components

Functional Components 12 minA React component is a JavaScript function, named with a capital letter, that returns the markup for one piece of the interface.

react / Function Components

Explore each scene at your own pace.

01 · The rule

The rule

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, not bookCard. 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 null to 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.