Capítulo 12 de 116

Chapter 12: Importing and Exporting Components

Core Idea

As components multiply, split them into separate files using standard JavaScript export/import — a file can have at most one default export but any number of named exports, and the export style you pick dictates the required import syntax.

Key Concepts

  • Root component file: the entry file (often App.js, or per-page in a file-based router) that other components eventually get imported into.
  • Three-step move: create a new file → export the component from it (default or named) → import it where it's used.
  • Default export: export default function Button() {}import Button from './Button.js' — the import name is arbitrary, doesn't need to match.
  • Named export: export function Button() {}import { Button } from './Button.js' — the name must match on both sides.
  • Convention: default export when a file exports exactly one component; named exports when it exports several. Mixing both in the same file is allowed but some teams avoid it for clarity.
  • File extension in imports is optional: './Gallery.js' and './Gallery' both work; the explicit .js is closer to native ES Modules semantics.
  • Avoid anonymous default exports (export default () => {}) — an unnamed component function makes debugging harder (stack traces, DevTools).

Reference Tables

SyntaxExport statementImport statement
Defaultexport default function Button() {}import Button from './Button.js';
Namedexport function Button() {}import { Button } from './Button.js';

Key Takeaways

  1. One default export per file, unlimited named exports — mixing is fine but pick one style per file for clarity if the team prefers.
  2. Default-import names are free-form (import Banana from './Button.js' still works); named-import names must match the export exactly.
  3. A single file can hold both a default export (e.g. Gallery) and a named export (e.g. Profile) simultaneously — the importing file then combines a default import and a { NamedThing } import from the same path.

Connects To

  • Ch 11 (Your First Component): the component being split out here.
  • Ch 41 (Reusing Logic with Custom Hooks): the same export/import mechanics apply to custom Hook files.