CodeOath
← All posts
React75 min total · 17 parts

React Fundamentals: Components, Hooks, and the Virtual DOM

Contents — Part 3 of 17: Components and Props
Part 3 of 17 · ~1 min

Components and Props

A component is just a function that returns JSX. Props are the arguments passed into it — read-only from the component's own point of view. A component must never reassign or mutate its own props.

function Avatar({ src, alt, size = 40 }) {
  return <img src={src} alt={alt} width={size} height={size} className="rounded-full" />;
}

<Avatar src={user.avatarUrl} alt={user.name} />
<Avatar src={user.avatarUrl} alt={user.name} size={80} />

Destructuring props in the function signature (as above) is the standard style — it documents exactly what a component accepts at a glance, and default values (size = 40) replace the old defaultProps API for function components.

The children prop

Anything nested between a component's opening and closing tags is passed to it as a special children prop:

function Card({ title, children }) {
  return (
    <div className="card">
      <h3>{title}</h3>
      {children}
    </div>
  );
}

<Card title="Profile">
  <p>This whole block is Card's `children`.</p>
</Card>

This is the foundation of composition in React — layout components (Card, Modal, Layout) accept arbitrary content via children instead of needing a prop for every possible thing that could go inside them. See the Composition Patterns chapter for where this pattern goes further.

Prop drilling

Passing a prop through several layers of components that don't use it themselves, just to get it to a deeply nested child, is called prop drilling. It's not wrong for one or two levels, but it's the problem Context (covered later) exists to solve at scale.