Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 132 ยท Components and Props

Your First Components

Learn what a React component is, how to write function components, name them, nest them into a tree and render the tree with createRoot, with live examples.

A React app is a tree of components. A component is a JavaScript function that returns a description of a piece of the screen: a button, a profile card, a whole page. You build small components, put them inside bigger ones, and the biggest one, usually called App, is the root of the tree. Everything you see in a React app is a component somewhere in that tree, or a plain HTML element that a component produced.

This lesson shows how to write a component, why the naming rules matter, how to nest components, and how React turns the tree into a real page. If JSX still looks strange, read JSX Basics first; this page uses it without much explanation. The next lesson adds the missing piece: passing data into components.

A component is a function that returns JSX

Here is the smallest useful component. It takes no input and returns a heading.

A function component

Three things happened.

  1. We defined a component: function Greeting() { ... }. Nothing is displayed yet; a definition is only a recipe.
  2. We used it by writing <Greeting />. It looks like an HTML tag but starts with a capital letter, and it means "put the output of the Greeting function here".
  3. We handed that request to createRoot(...).render(...). createRoot takes a real DOM element (the empty <div id="root"> on the page) and gives back a root object. Calling render on it tells React to draw the tree inside that element.

Every example in this tutorial is a complete module: it imports what it needs and ends with the createRoot line. In a real project that line lives in one file (often main.jsx) and is written once, for the root component only.

Naming: the capital letter is not optional

React decides what a tag means by its first letter.

  • <div>, <p>, <button>: lowercase means a built-in HTML (or SVG) element.
  • <Greeting />, <ProfileCard />: uppercase means "this is a component; call it".

If you name a component in lowercase and use it as a tag, React does not call it. It creates an element literally named greeting. The browser treats it as an unknown, empty element, and in development React logs a console error: The tag <greeting> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter. The output is just missing:

A lowercase component name is ignored (fails on purpose)

Only the paragraph is visible. Rename the function and the tag to Greeting and the heading shows up. This is why every component in React is PascalCase (each word starts with a capital letter, no separators): UserAvatar, ShoppingCart, TodoItem.

Use a name that says what the component is, not where it is used: Avatar, not HeaderLeftThing. A good name makes the JSX read almost like a sentence: <Sidebar><Avatar /><Menu /></Sidebar>.

Components return one thing

A component can return JSX, a string, a number, null, or an array of those. What it cannot do is return two sibling elements without a wrapper, because a function returns a single value:

Two siblings without a wrapper (fails on purpose)

Babel stops with Adjacent JSX elements must be wrapped in an enclosing tag. Fix it by wrapping the elements in a <div>, or, when you do not want an extra element in the DOM, in a fragment: <> and </>. A fragment groups children without adding anything to the page.

A fragment as the wrapper

The console shows children of #root: 0 at the moment the log line runs, because React renders asynchronously after render is called; a moment later the root holds two elements (h1 and p) and no wrapper. The parentheses after return are not part of React: they stop JavaScript's automatic semicolon insertion from ending the statement at the end of the first line.

Fragments with keys, and what fragments cannot do

The short <>...</> syntax cannot take any props. When you render a list where each item produces several sibling elements (a term and its definition, for example), the fragment itself needs a key, and for that you must import Fragment and write the long form: <Fragment key={id}>. A fragment accepts only key (and ref in recent React versions), so it cannot carry a className, an event handler or styles. If you need any of those, use a real element.

A fragment also hides nothing from the layout rules of the parent: if a component returns a fragment with three children and you place it inside a flex or grid container, those three children become the container's items, since no wrapper exists between them.

A keyed fragment in a list

Writing <> instead of <Fragment key=...> here would give React's "each child in a list should have a unique key" warning, and wrapping each pair in a <div> would make the dl markup invalid HTML.

Components are used, never called

A component is a function, so you might be tempted to write Greeting() instead of <Greeting />. Do not. When you write the tag, React calls the function for you, at the right time, and gives the call its own place in the tree: its own state, its own lifecycle. Calling it yourself pastes its output into the parent as if you had written that JSX by hand, and any hooks inside would silently belong to the parent. The same goes for defining a component inside another component: the inner function is a brand new function on every render, so React sees a different component each time and throws away its state. Define components at the top level of the file.

Nesting: building a tree

Components become powerful when they use each other. A component can render other components wherever it could render an HTML element.

A tree of components

ProfileCard is defined once and used twice, so two cards appear. Each use is an independent instance with its own place in the tree, which will matter when components have state. The tree looks like this:

TEXT
App
โ””โ”€โ”€ main
    โ”œโ”€โ”€ h1
    โ”œโ”€โ”€ ProfileCard
    โ”‚   โ””โ”€โ”€ section
    โ”‚       โ”œโ”€โ”€ Avatar  โ†’ span
    โ”‚       โ””โ”€โ”€ Bio     โ†’ p
    โ””โ”€โ”€ ProfileCard
        โ””โ”€โ”€ section
            โ”œโ”€โ”€ Avatar  โ†’ span
            โ””โ”€โ”€ Bio     โ†’ p

Components are the nodes with capital letters; HTML elements are the leaves React finally gives to the browser. React walks the tree from the root, calls each component to learn what it returns, and repeats until only HTML elements remain. That walk is the render. The browser DOM is then updated to match the result in a separate step called the commit (see How React Works).

Why a component, and when to make one

Why split the UI into components at all? Four practical reasons:

  • Reuse. The same card, button or row appears in many places and is written once.
  • Readability. <ProfileCard /> tells you more than forty lines of nested divs.
  • Isolation. A component owns its markup, its logic and (soon) its state; changing one does not require reading the others.
  • Testing and change. Small units are easy to check and easy to replace.

A good rule: extract a component when a piece of UI has a name you can say out loud, when it repeats, or when a function grows too large to understand at a glance. Do not extract on day one for every div; extra layers have a reading cost too. Designing Components goes deeper.

One component per concern, usually per file

In real projects each component usually lives in its own file and is exported:

JSX
// ProfileCard.jsx  (read-only: separate files need a project, see Setting Up a React Project)
import Avatar from './Avatar.jsx';
import Bio from './Bio.jsx';

export default function ProfileCard() {
  return (
    <section>
      <Avatar />
      <Bio />
    </section>
  );
}

Our editor runs a single module, so the live examples keep several components in one file. The code is the same either way; only import and export lines differ. See Setting Up a React Project.

Small helper components used by only one parent can stay in the same file. When a component is shared or large, give it its own file named after it (ProfileCard.jsx).

Components can have logic

A component is ordinary JavaScript before it reaches the return. You can compute values, call functions and declare variables:

Plain JavaScript inside a component

Notice the fixed numbers: a component should compute its output only from what it is given (and, later, its state). Reading the current time or a random number while rendering makes the output unpredictable; Keeping Components Pure explains why that matters.

A short history: why not classes?

Older React code, and many older tutorials, define components as ES6 classes with a render() method:

JSX
// Read-only: the old style. Do not write new code like this.
class Greeting extends React.Component {
  render() {
    return <h1>Hello</h1>;
  }
}

Class components still work, but since hooks arrived (React 16.8, 2019) every feature classes offered has a function equivalent that is shorter and easier to reuse. All new React code, official docs included, uses function components. The one remaining job for a class is the error boundary. When you read an old codebase, treat classes as a dialect you only need to read, not write.

Common mistakes

  • Lowercase component name. The tag is treated as HTML; nothing renders.
  • Calling a component like a function (Greeting()). Use <Greeting />.
  • Defining a component inside another component. It resets state on every parent render. Move it to the top level.
  • Forgetting to return. A function with braces and no return gives undefined, and the component renders nothing. (Arrow functions with a plain expression body return implicitly; with braces they do not.)
  • Two roots. Wrap siblings in a fragment or an element.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line renders the component named ProfileCard?

    Components are used as JSX tags that start with a capital letter. A lowercase tag is treated as a built-in HTML element.
  2. 2. What does a function component return?

    A component returns JSX (React elements), text, numbers, arrays of those, or null. React turns that description into real DOM nodes.
  3. 3. You wrote a component that returns <h1>A</h1> and <p>B</p> side by side. How do you fix the error?

    A function returns one value, so JSX must have a single root. A fragment groups the siblings without adding an extra DOM element.
  4. 4. What is wrong with writing Greeting() instead of <Greeting /> inside another component?

    Using the tag lets React call the function and give it a place in the tree. Calling it yourself just inlines its output into the parent, and hooks inside would belong to the parent.
  5. 5. Why should components be defined at the top level of a file instead of inside another component?

    React identifies a component by its function identity. A new function each render means a new component type, so the old subtree is unmounted and the new one mounted, losing state.

Summary

  • A component is a function that returns JSX; you use it as a tag, and React calls it.
  • Component names are PascalCase. Lowercase tags are HTML elements.
  • A component returns a single root; use a fragment <>...</> when you do not want an extra element.
  • Components nest into a tree. Each use of a component is its own instance.
  • Never call components as functions and never define them inside other components.
  • Function components are the modern standard; classes remain only for error boundaries.

Next: Props