DEV Community

Cover image for Class Based Components DEEP DIVE
Tushar
Tushar

Posted on

Class Based Components DEEP DIVE

Introduction to Class-Based Components in React

In this Blog we will cover what is ClASS BASED components and how to pass PROP in class based component

Class-based components are a foundational concept in React. Although the trend has shifted towards functional components with hooks, understanding class-based components is essential for working with existing codebases and grasping React's core concepts.

Syntax of Class-Based Components

Class-based components in React are defined using ES6 classes that extend the React.Component class. Here’s a basic example:

import React, { Component } from 'react';

class UserClass extends Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

export default UserClass;

Enter fullscreen mode Exit fullscreen mode
  • Extends: The extends Component syntax informs React that UserClass is a class-based component.
  • Render Method: The render method returns the JSX that will be displayed on the screen.
class userClass extends React.Component{

}
Enter fullscreen mode Exit fullscreen mode

To summarize, we create a JavaScript class UserClass which extends from React.Component that comes from the React library.

How to pass props inside CLASS based Component

Props are used to pass data from parent components to child components. Here's how to work with props in class-based components.

Sending Props:

<UserClass name="John Doe" />

Enter fullscreen mode Exit fullscreen mode

Receiving Props:
We will create a constructor and this constructor will recieve the PROPand will use SUPER keryword to recieve and we always have to write it otherwise it will throw error.

class UserClass extends Component {
  constructor(props) {
    super(props);
    console.log(this.props.name);
  }

  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

Enter fullscreen mode Exit fullscreen mode
  • Constructor: Initializes the component and receives props.
  • Super: Passes the props to the base Component class.
  • this.props: Accesses the props within the component.

The console will show the value of the prop.

Function Components Comparison

For comparison, here’s how the same task is done using functional components:

const UserFunction = (props) => {
  return <h1>Hello, {props.name}</h1>;
}

Enter fullscreen mode Exit fullscreen mode

To use the prop within a class-based component, you would write this.props.name.

The method of sending props is the same for both class-based and functional components. The primary difference lies in how props are received and used: class-based components use the constructor and the super keyword.

Top comments (0)