View Categories

React Class Components

Definition: Class components are ES6 classes that extend React.Component. They provide the ability to manage state and lifecycle hooks in React.

Usage: Before React 16.8, class components were essential for managing state. Post-Hooks, they are still supported but are used less often in favour of functional components.

Creating a Class Component #

  • Syntax:
class ComponentName extends React.Component {
  render() {
    return <h2>Hello, I am a component!</h2>;
  }
}

Naming Rule: Component names must begin with an uppercase letter.

Rendering:

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<ComponentName />);

State in Class Components #

  • State Definition:
    • Initialised in the constructor using this.state.
    • Accessed using this.state.propertyName.
class MyComponent extends React.Component {
  constructor() {
    super();
    this.state = { key: "value" };
  }
}

Updating State:

  • Use this.setState() to ensure re-rendering.
this.setState({ key: "new value" });

Example:

class Car extends React.Component {
  constructor() {
    super();
    this.state = { color: "red" };
  }
  changeColor = () => {
    this.setState({ color: "blue" });
  };
  render() {
    return (
      <div>
        <h2>My Car is {this.state.color}</h2>
        <button onClick={this.changeColor}>Change Color</button>
      </div>
    );
  }
}

Props in Class Components #

  • Definition: Props are immutable and passed to components like function arguments.
  • Usage:
class Car extends React.Component {
  render() {
    return <h2>I am a {this.props.color} car!</h2>;
  }
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car color="red" />);

Lifecycle Methods #

React class components have a well-defined lifecycle:

1. Mounting Phase

  • constructor(): Initialise state and props.
  • render(): Mandatory, outputs the component’s JSX.
  • componentDidMount(): Runs after the component is rendered into the DOM.
class Header extends React.Component {
  constructor() {
    super();
    this.state = { color: "red" };
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({ color: "blue" });
    }, 1000);
  }
  render() {
    return <h2>My Favorite Color is {this.state.color}</h2>;
  }
}

2. Updating Phase

  • getDerivedStateFromProps(): Sync state with props before rendering.
  • shouldComponentUpdate(): Controls whether the component should re-render.
  • render(): Re-renders the JSX.
  • componentDidUpdate(): Called after the component updates.

3. Unmounting Phase

  • componentWillUnmount(): Cleanup tasks before the component is removed.

Components in Components #

Components can be nested:

class Car extends React.Component {
  render() {
    return <h2>I am a Car!</h2>;
  }
}

class Garage extends React.Component {
  render() {
    return (
      <div>
        <h1>Who lives in my Garage?</h1>
        <Car />
      </div>
    );
  }
}

Organising Components in Files #

  • Create separate files for components:
    • Car.js:
import React from "react";
class Car extends React.Component {
  render() {
    return <h2>I am a Car!</h2>;
  }
}
export default Car;

Import and use:

import Car from "./Car";
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);

Final Notes #

While class components remain supported, functional components with hooks are often preferred for simplicity and cleaner code. This guide ensures you understand the fundamentals of class components if you need them for legacy code or specific use cases.

Want to learn React with an instructor, either offline or online? Find experienced tutors near you and join Coaching Wallah—completely free for students!

Leave your comment