Class Components in React

Uman Tabassum
2 min readMay 27, 2021

In react we have two components to render our code. They are functional components and class components.

Class Components

let’s discuss in brief functional components and it’s functionality in react to render the methods.

Photo by Nubelson Fernandes on Unsplash

Class components are the components that use the render method and within the render method, we return HTML code or the react elements created with JSX.

Example:

import React from ‘react’;

class Welcome extends React.component{

render(){

return(

//Some JSX CODE

<h1>hello world</h1>

);

}

};

This is an example of a class component in react. In the above example, the class components use the render() method to return the JSX code. Class components are more feature-rich, maintain their own private data -state, complex UI logic, provide lifecycle hooks. They are known as stateful container components.

In class components, we use the constructor( ) method. The constructor ( ) method is used to initialize the objects in class components. In this case, the object refers to the state, we initialize the state in the constructor( ) and we can bind to the method.

The way to initialize state in the constructor method is:

constructor(props) {
super(props);
this.state = {
name : "Cleo";
};
}
class Welcome extends React.component{
render()
{
return(
<div>
<h1>My name is {this.state.name} </h1>
</div>
)}
}

props refer to properties that can be rendered from the parent component and whenever you wanted to initialize objects or to read properties from the parent class we use the super ( ) keyword. In the above code, I have created an object called name, and this name is initialized to “ Cleo ”.Within the class component, the javascript code is rendered in curly brackets { } and this.state.name gives the initialized value i.e Cleo. Ok cool. I think the things got cleared.

In this way we render components using class in react.

--

--

Uman Tabassum

A full-stack web developer and a Robotics enthusiast