React Class Components

Introduction to React Components

React Components are the building blocks of any React application. They are reusable and can be nested inside other components, allowing for a modular and scalable approach to building user interfaces.

Creating a Class Component

A Class Component in React is defined using the class keyword and extends React.Component. Here’s a simple example:

import React, { Component } from 'react';

class Welcome extends Component {
  render() {
    return <h1>Hello, World!</h1>;
  }
}

The Component Constructor

Class Components can have constructors, where you can initialize state and bind methods. The constructor is the first function called when a component is instantiated.

constructor(props) {
  super(props);
  // Initialization code here
}

Understanding Props

Props (short for properties) are read-only attributes used to pass data from a parent component to a child component.

Props in the Constructor

You can access props in the constructor of a Class Component:

constructor(props) {
  super(props);
  this.state = { greeting: props.greeting };
}

Nesting Components

React allows components to be nested within other components, promoting reusability and modularity. For example:

class App extends Component {
  render() {
    return (
      <div>
        <Welcome />
      </div>
    );
  }
}

Organizing Components in Files

It’s a best practice to place each React Component in its own file to keep the codebase clean and manageable.

React Class Component State

State in a React Class Component is a JavaScript object where you store property values that belong to the component.

Creating the State Object

The state object is initialized in the constructor:

constructor(props) {
  super(props);
  this.state = { counter: 0 };
}

Using the State Object

State can be accessed via this.state and is used within the render() method to display dynamic data:

render() {
  return <h1>{this.state.counter}</h1>;
}

Changing the State Object

State should be updated using the setState() method:

this.setState({ counter: this.state.counter + 1 });

Lifecycle of Components

Class Components have several lifecycle methods, such as componentDidMount, componentDidUpdate, and componentWillUnmount, that allow you to run code at specific points in the component’s life.