Computer scienceFrontendReactReact Components

Class components

7 minutes read

React, a popular JavaScript library for building user interfaces, provides developers with two main ways to create components: functional components and class components. While functional components have gained popularity with the introduction of hooks, class components have been the cornerstone of React development for many years. In this topic, we will delve into the world of class components, exploring their structure, lifecycle methods, and the scenarios where they are still relevant.

Anatomy of a class component

Class components in React are JavaScript ES6 classes that extend the React.Component class. They encapsulate the logic and state of a UI element. Let's take a look at a simple class component:

import React from "react";
 
class App extends React.Component {
  render() {
    return <h1>Hello, World!</h1>;
  }
}
 
export default App;

This code defines a React class component named App. It extends the React.Component class. The render method returns a JSX element, in this case, an <h1> element displaying the text "Hello, World!". Finally, the component is exported as the default export of the module.

Constructor and state

One key feature of class components is the ability to hold and manage local state. This is achieved through the constructor method. Let's enhance our previous example by adding a state to our class component:

import React, { Component } from "react";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      greeting: "Hello",
    };
  }

  render() {
    return <h1>{this.state.greeting}, World!</h1>;
  }
}

export default App;

In this code, we've added a constructor method, where we initialize the component's state using this.state. The initial state contains a property greeting set to "Hello". The render method now uses this state to dynamically display the greeting.

Functional to class component

If you have a functional component and need to convert it to a class component, it's a straightforward process. Here's a quick guide:

Functional component:

import React from 'react';

const MyFunctionalComponent = () => {
  return <h1>Hello, I'm a functional component!</h1>;
};

Class component:

import React from "react";
 
class App extends React.Component {
  render() {
    return <h1>Hello, I'm a class component!</h1>;
  }
}
 
export default App;

Simply, create a class that extends React.Component and move the component logic into the render method.

While functional components and hooks have become the standard in modern React development, there are scenarios where class components are still relevant. If you are working with an older codebase or a library that relies on class components, understanding their structure and lifecycle methods remains valuable.

Event handling and props usage

Event Handling in Class Components: Handling events in class components involves defining methods to respond to specific events. For example, handling a button click event:

class App extends Component {
  handleClick = () => {
    console.log("Button clicked!");
  };

  render() {
    return <button onClick={this.handleClick}>Click me</button>;
  }
}

The above code snippet defines a React class component named "App" that extends the "Component" class. Inside the class, there is a method called handleClick, which logs a message to the console when called. In the render method, a button element is returned with an onClick event handler set to the handleClick method. The use of the "this" keyword in this.handleClick is crucial within class components, as it refers to the current instance of the class and allows access to class methods and properties. In this case, this.handleClick ensures that the handleClick method is correctly bound and triggered when the button is clicked.

Props Usage in Class Components: Using props in class components is straightforward. Here's an example:

class Greeting extends Component {
  render() {
    return <h1>{this.props.message}</h1>;
  }
}

// Usage
const App = () => <Greeting message="Hello, World!" />;

The above code snippet defines a class component called "Greeting" that extends the "Component" class. Inside the component's "render" method, there is an h1 element containing the text retrieved from the "message" prop using this.props.message. The "message" prop is a property that can be passed to the "Greeting" component when it is used elsewhere in the application. In the usage example, a functional component named "App" is defined, and it renders an instance of the "Greeting" component. The "message" prop is set to "Hello, World!" when the "Greeting" component is invoked within the "App" component.

This illustrates the concept of props in React, which allows data to be passed from a parent component (in this case, "App") to a child component ("Greeting"). Props provide a way to customize and configure components dynamically based on the needs of the application.

Advantages and disadvantages

Class components have distinct advantages and disadvantages. Understanding these can guide your decision on when to use class components over functional components.

Advantages:

  • Local State Management: Class components allow for easy management of local state using the constructor method.

  • Lifecycle Methods: Although the section on lifecycle methods is omitted here, class components offer lifecycle methods for specific actions during a component's lifecycle.

Disadvantages:

  • Verbose Syntax: Class components typically have more boilerplate code than functional components, making them more verbose.

  • Complexity: As your application grows, class components can become more complex to manage.

Read more on this topic in Exploring Python Magic Method Operators on Hyperskill Blog.

Conclusion

Class components have been a fundamental part of React development, providing a robust structure and a clear way to manage state and lifecycle events. While functional components and hooks have become the preferred choice for many developers, understanding class components is crucial for maintaining and navigating existing codebases.

7 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo