Hackforge Academy

Category: react

class component in React

Published on 10 Apr 2026

Explanation

A class component in React is a JavaScript ES6 class that extends React.Component. It must include a render() method that returns JSX to display UI.

Code:

import React, { Component } from 'react';

class Welcome extends Component {
  render() {
    return <h1>Hello React Class Component
</h1>;
  }
}

export default Welcome;

Explanation

Class components can receive props and access them using this.props inside the render() method.

Code:

import React, { Component } from 'react';

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

export default Welcome;

Explanation

Class components can manage state using a constructor and this.state object. State allows dynamic updates in UI.

Code:

import React, { Component } from 'react';

class Counter extends Component {
  constructor(props) {
    super(props);

    this.state = {
      count: 0
    };
  }

  render() {
    return <h2>{this.state.count}</h2>;
  }
}

export default Counter;

Explanation

State in class components is updated using this.setState() method instead of direct assignment. render() { return ( <div> <h2>{this.state.count}</h2> <button onClick={this.increment}> Increase</button> </div> ); }

Code:

import React, { Component } from 'react';

class Counter extends Component {
  constructor(props) {
    super(props);

    this.state = {
      count: 0
    };
  }

  increment = () => {
    this.setState({ count: 
this.state.count + 1 });
  };
}

export default Counter;

Explanation

Lifecycle methods like componentDidMount() are available in class components and execute at different stages of component life.

Code:

import React, { Component } from 'react';

class Example extends Component {
  componentDidMount() {
    console.log('Component Mounted');
  }

  render() {
    return <h1>Lifecycle Example</h1>;
  }
}

export default Example;

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community