Capítulo 11 de 116

Chapter 11: Your First Component

Core Idea

A React component is just a JavaScript function, capitalized, that returns JSX markup — components are the reusable UI building block everything else in React composes from, the same way <article>/<h1>/<li> compose an HTML document.

Key Concepts

  • Definition steps: export default (standard JS, marks the file's main function for import elsewhere) + function ComponentName() {} (capitalized name — required, or the JSX tag won't be recognized as a component) + a return of JSX markup.
  • Return-statement pitfall: if the returned JSX isn't on the same line as return, it must be wrapped in parentheses — otherwise JavaScript's automatic semicolon insertion silently returns undefined.
  • Using a component: nest it like any tag, e.g. <Profile />. Casing is the signal React uses: lowercase (<section>) means "host HTML element," capitalized (<Profile />) means "my component."
  • Parent/child: a component that renders another (possibly several times) is its parent; each rendered instance is a child — this is how one Profile definition becomes three <img> tags in the final HTML.
  • Never nest component definitions. Defining function Profile() {} inside function Gallery() {} is slow and causes state bugs (see Ch 30, Preserving and Resetting State). Always declare components at the top level; pass data down via props (Ch 15) instead.
  • Components all the way down: most apps have one "root" component (often framework-generated), but even single-use pieces like a whole sidebar or page are commonly written as components purely for code organization.

Code Examples

function Profile() {
  return <img src="..." alt="Katherine Johnson" />;
}

export default function Gallery() {
  return (
    <section>
      <h1>Amazing scientists</h1>
      <Profile />
      <Profile />
    </section>
  );
}
  • What it demonstrates: a parent component (Gallery) rendering a child component (Profile) multiple times — the core composition mechanic of React.

Key Takeaways

  1. Two hard rules distinguish a React component from a regular JS function: the name must start with a capital letter, and it must return JSX.
  2. Nesting component definitions (not usage) inside each other is a correctness bug, not just a style issue — it resets state on every parent re-render.
  3. export default vs. named export controls how the file gets imported elsewhere — the full rules are in Ch 12.

Connects To

  • Ch 12 (Importing and Exporting Components): how to split this component into its own file.
  • Ch 15 (Passing Props to a Component): how a parent passes data down instead of nesting definitions.
  • Ch 30 (Preserving and Resetting State): the concrete bug caused by nested component definitions.