React Tutorial For Beginners - Working on Class Components in React

Introduction

React is an Open Source JavaScript library. It is used for developing scalable, simple, and fast front-ends for web & mobile applications. It handles the view layer of mobile and web applications. React is flexible and can be used in any application.

Description

In this article, we learn about React Class Components. Also, we know the steps to create React Class Components and how to render React Class Components. Here, we discuss React Class Components with some examples. Also, how to work on React on both Desktop and Mobile platforms. React lets us define components as classes or functions. Here we will understand Class Components.

Please visit the React articles to understand the beginning.

The below React articles are for a basic understanding of React sample applications.

What is the React Component?

  • React Components are the building blocks of the React application.
  • React Components allow us to split the UI into independent and reusable parts.
  • React app will have many components like the header component, navbar component, footer component and content component.
  • React Component is a JavaScript class or function that accepts inputs, which are properties(props).
  • It returns a React element that describes how a section of the User Interface should appear.
  • React components can be created as a Function Component or Class Component.

React Component consists of the following parts.

  • Template using HTML
  • User Interactivity using JS
  • Applying Styles using CSS

Class Components in React

To define a React component class, we have to create a class and extend React.Component class. Here I create an Employee Component and this Component should return the Element which displays Employee Details.

index.js code

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class Employee extends React.Component {
  render() {
    return (
      <div>
        <h2>Display Employee Details Using Class Component</h2>
        <p>
          <label>Employee ID: <b>{this.props.Id}</b></label>
        </p>
        <p>
          <label>Employee Name: <b>{this.props.Name}</b></label>
        </p>
        <p>
          <label>Employee Location: <b>{this.props.Location}</b></label>
        </p>
        <p>
          <label>Employee Salary: <b>{this.props.Salary}</b></label>
        </p>
        <br />
        <h2>Employee & Department Details In Table</h2>
        <table>
          <thead>
            <tr>
              <th scope="col">Employee ID</th>
              <th scope="col">Employee Name</th>
              <th scope="col">Employee Location</th>
              <th scope="col">Employee Salary</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>{this.props.Id}</td>
              <td>{this.props.Name}</td>
              <td>{this.props.Location}</td>
              <td>{this.props.Salary}</td>
            </tr>
          </tbody>
        </table>
      </div>
    );
  }
}

const element = (
  <Employee 
    Id="101" 
    Name="Satyaprakash Samantaray" 
    Location="Bengaluru" 
    Salary="61000" 
  />
);

ReactDOM.render(element, document.getElementById("root"));

Create Employee class and extend it from React.Component. Output of any Class Component we create is dependent on the return value of a Method Called render(). The render() method is the only required method that needs to be implemented in a class component. Here we create a div element which displays employee details like ID, Name, Location, Salary and return the div from this Method. To access the attributes that will be passed to this Component Class, in React we use this.props. Attribute Name (e.g. {this.props.Name}). this.props contains the props that were defined by the caller of this component.

Calling the Class Component and rendering remains the same as the Function Component.

const element = (
  <Employee 
    Id="101" 
    Name="Satyaprakash Samantaray" 
    Location="Bengaluru" 
    Salary="61000" 
  />
);

ReactDOM.render(element, document.getElementById("root"));

Output

Output

Call a Component in another Class Component

Now we have the Department Component as Employee Component. So we create a Class, name it as Department, and extend React.Component. We will return an Element which displays Department Information like Department Name, Head of the Department Name, and use this Component in the Employee Component.

index.js code

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class Employee extends React.Component {
  render() {
    return (
      <div>
        <h2>Display Employee Details Using Class Component</h2>
        <p>
          <label>Employee ID: <b>{this.props.Id}</b></label>
        </p>
        <p>
          <label>Employee Name: <b>{this.props.Name}</b></label>
        </p>
        <p>
          <label>Employee Location: <b>{this.props.Location}</b></label>
        </p>
        <p>
          <label>Employee Salary: <b>{this.props.Salary}</b></label>
        </p>
        <Department DeptName={this.props.DeptName} HeadName={this.props.HeadName} />
        <br />
        <h2>Employee & Department Details In Table</h2>
        <table>
          <thead>
            <tr>
              <th scope="col">Employee ID</th>
              <th scope="col">Employee Name</th>
              <th scope="col">Employee Location</th>
              <th scope="col">Employee Salary</th>
              <th scope="col">Department Name</th>
              <th scope="col">Head Name</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>{this.props.Id}</td>
              <td>{this.props.Name}</td>
              <td>{this.props.Location}</td>
              <td>{this.props.Salary}</td>
              <td>{this.props.DeptName}</td>
              <td>{this.props.HeadName}</td>
            </tr>
          </tbody>
        </table>
      </div>
    );
  }
}

class Department extends React.Component {
  render() {
    return (
      <div>
        <h2>Display Department Details Using Class Component</h2>
        <p>
          <label>Dept Name: <b>{this.props.DeptName}</b></label>
        </p>
        <p>
          <label>Head Name: <b>{this.props.HeadName}</b></label>
        </p>
      </div>
    );
  }
}

const element = (
  <Employee 
    Id="101" 
    Name="Satyaprakash Samantaray" 
    Location="Bengaluru" 
    Salary="61000"
    DeptName="IT Department" 
    HeadName="Ranjit Meheta" 
  />
);

ReactDOM.render(element, document.getElementById("root"));

Here the Department class component is created.

class Department extends React.Component {

   render(){
     return <div>
       <h2>Display Department Details Using Class Component</h2>
       <p>
         <label>Dept Name : <b>{this.props.DeptName}</b></label>
       </p>
       <p>
         <label>Head Name : <b>{this.props.HeadName}</b></label>
       </p>
       </div>;
   }
 }

Call the Department class component inside the Employee class component.

<Department 
  DeptName={this.props.DeptName} 
  HeadName={this.props.HeadName} 
/>

Set both class component's properties values and assign to the element.

const element = (
  <Employee 
    Id="101" 
    Name="Satyaprakash Samantaray" 
    Location="Bengaluru" 
    Salary="61000"
    DeptName="IT Department" 
    HeadName="Ranjit Meheta" 
  />
);

Output

Class component

Props are Read-Only

We declare a component as a function or a class, it must never modify its own props. let's go and add a Constructor to the Employee Component Class, and inside the Constructor, let's try to log the Property Object.

index.js Code

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class Employee extends React.Component {
  constructor(){
    console.log( this.props);
   } 
   render(){
     return <div>
       <h2>Display Employee Details Using Class Component</h2>
       <p>
         <label>Employee ID : <b>{this.props.Id}</b></label>
       </p>
       <p>
         <label>Employee Name : <b>{this.props.Name}</b></label>
       </p>
       <p>
         <label>Employee Location : <b>{this.props.Location}</b></label>
       </p>
       <p>
         <label>Employee Salary : <b>{this.props.Salary}</b></label>
       </p>
       <Department DeptName={this.props.DeptName} HeadName={this.props.HeadName}/>
       <br />
            <h2>Employee & Department Details In Table</h2>
            <table>
                <thead>
                    <tr>
                        <th scope="col">Employee ID</th>
                        <th scope="col">Employee Name</th>
                        <th scope="col">Employee Location</th>
                        <th scope="col">Employee Salary</th>
                        <th scope="col">Department Name</th>
                        <th scope="col">Head Name</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>{this.props.Id}</td>
                        <td>{this.props.Name}</td>
                        <td>{this.props.Location}</td>
                        <td>{this.props.Salary}</td>
                        <td>{this.props.DeptName}</td>
                        <td>{this.props.HeadName}</td>
                    </tr>
                </tbody>
            </table>
       </div>;
   }
 }

 class Department extends React.Component {

   render(){
     return <div>
       <h2>Display Department Details Using Class Component</h2>
       <p>
         <label>Dept Name : <b>{this.props.DeptName}</b></label>
       </p>
       <p>
         <label>Head Name : <b>{this.props.HeadName}</b></label>
       </p>
       </div>;
   }
 }

 const element=<Employee Id="101" Name="Satyaprakash Samantaray" Location="Bengaluru" Salary="61000"
               DeptName="IT Department" HeadName="Ranjit Meheta"/>

 ReactDOM.render(element,document.getElementById("root"));

This Code will throw an Error and It is expecting us to call the Base Class Constructor.

constructor(){
    console.log( this.props);
   }

Base Class Constructor.

We fix that by using Super();

constructor(){
    super();
    console.log( this.props);
   }

In console, it shows undefined.

Console

After adding the Base Class Constructor call, if we look at the Console in the browser, we get props value as undefined. To make sure that the props object can be accessed in the constructor, we have to add this parameter to the constructor and pass it to the base class constructor as well. Now if we save this, we can see that the object data in the Console log.

constructor(props){
    super(props);
    console.log( this.props);
   }

Console log

Now if we try to change the Name using the props object, we can see an error, and the error says.

constructor(props){
      super(props);
      console.log( this.props);
      this.props.Name="Kulu";
     }

Uncaught TypeError: Cannot assign to read only property 'Name' of object '#<Object>'

Uncaught TypeError

Note

  • React has a single strict rule about Props are read-only.
  • React application UIs are dynamic and change over time. A new concept named “state” allows React components to change their output over time in response to user actions without violating this rule.

When to use Class Component over Function Component?

If the below features are required, then we will go for Class Component and in the rest of the cases, we can go for Function Component.

  • Managing State of the Components
  • Adding Life Cycle Methods to Components
  • Need to Write Logic for Event Handlers

Write React Code using Online Editor

You can play with the React application Mobile platform using the below steps. Let's open the below URL and start coding.

Then open the below URL to add CDN links so that React can understand the syntax. Select JavaScript Preprocessor: babel.

The steps are already discussed in Part-4 Working on Function Components in React

Summary

In this write-up, we have learned the details below.

  • React Components and their types
  • Know about React Class components
  • Call a Class component in another Class component
  • Props are Read-Only and check different scenarios in the browser console
  • Features of the Class component

Thank You & Stay Tuned For More!

Up Next
    Ebook Download
    View all
    Learn
    View all