Web Unit 3 Sprint 9 - Class Components & Testing

Module 1: Class Components

In this module, you'll learn about class components in React and how they differ from functional components. You'll understand the lifecycle methods and state management in class components.

Class components have been a significant part of the React ecosystem because they provide functionality that wasn't initially available with functional components. Though hooks now bring similar capabilities to functional components, many existing projects still use class components, making it essential to understand how to work with them.

The focus will be on understanding React's Component base class, which allows access to lifecycle methods, state management, and event handling in a class-based approach.

Learning Objectives

Remember the "CCR" approach to building class components:

  1. Class - Declare your class and extend React.Component
  2. Constructor - Set up state and bind methods
  3. Render/Return - Render UI to the DOM

Content

Class Components

Key Concepts

  • Class components extend the React.Component base class
  • The constructor method initializes state and binds event handlers
  • Always call super() in the constructor to access this
  • State in class components is always an object accessed via this.state
  • State must be updated using this.setState() method

The React Component Lifecycle

The Three Phases of Component Lifecycle

  • Birth/Mounting Phase - Component is built and inserted into the DOM
  • Growth/Updating Phase - Component updates when state or props change
  • Death/Unmounting Phase - Component is removed from the DOM

React Component LifeCycle - Mounting Phase

Mounting Phase Methods

  • constructor() - Initialize state and bind methods
  • render() - Return JSX to be rendered
  • componentDidMount() - Runs after component is mounted to the DOM, perfect for data fetching

Simulating interactions with userEvent

Key Testing Concepts

  • Event handlers in class components need to be bound to the class instance
  • userEvent provides a way to simulate user interactions in tests
  • Testing helps verify component behavior when users interact with it

Practice Activities

Additional Resources