Back to Curriculum

Components and Props

📚 Lesson 2 of 18 ⏱️ 45 min

Components and Props

45 min

Components are the building blocks of any React app. A component is a self-contained, reusable piece of UI.

Props (short for properties) are read-only attributes that are passed from a parent component to a child component.

Props allow you to create dynamic and configurable components.

Functional components are the modern standard in React, replacing class components for most use cases. They're simpler, more readable, and work seamlessly with hooks.

Props are immutable within a component - you cannot modify props directly. This ensures predictable data flow and makes components easier to reason about.

Component composition is a powerful pattern where you build complex UIs by combining smaller, focused components together.

Key Concepts

  • Components are reusable, self-contained pieces of UI.
  • Props are read-only data passed from parent to child components.
  • Functional components are the preferred way to write React components.
  • Component composition allows building complex UIs from simple pieces.
  • Props flow down the component tree in a unidirectional manner.

Learning Objectives

Master

  • Creating functional components with proper syntax
  • Passing and receiving props in components
  • Understanding prop types and default values
  • Composing multiple components together

Develop

  • Component design and reusability thinking
  • Understanding data flow in React applications
  • Breaking down UI into logical component structures

Tips

  • Use descriptive prop names that clearly indicate their purpose.
  • Destructure props in the function signature for cleaner code.
  • Provide default values for optional props using default parameters.
  • Keep components small and focused on a single responsibility.

Common Pitfalls

  • Trying to modify props directly (props are read-only).
  • Creating components that are too large and do multiple things.
  • Not using PropTypes or TypeScript for prop validation.
  • Passing too many props (consider using context or composition).

Summary

  • Components are reusable UI building blocks in React.
  • Props enable data flow from parent to child components.
  • Functional components are the modern standard.
  • Component composition is key to building maintainable UIs.

Exercise

Create a `Greeting` component that accepts a `name` prop and displays a personalized greeting.

function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

// Usage: <Greeting name="Sarah" />

Exercise Tips

  • Use destructuring: function Greeting({ name }) for cleaner code.
  • Add PropTypes for type checking in development.
  • Consider adding a default value if name is optional.
  • Test your component with different prop values.

Code Editor

Output