Enterprise Verified
Academy Frontend Web Development REACT React Class Components
Advertisement
Google AdSense Slot (LEADERBOARD)
Automated High-CTR Ad Rail • Set Publisher ID in config/adsense.php
Legacy Patterns 7 min read • Chapter 9 of 26

React Class Components

Understand ES6 Class Components, the render() method, this.state, this.setState(), and lifecycle methods for maintaining older codebases.

Before React 16.8 and the introduction of Hooks, Class Components were the only way to track state and lifecycle events. Knowing class components is essential when working with existing legacy codebases.

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  render() {
    return (
      <button onClick={() => this.setState({ count: this.state.count + 1 })}>
        Count: {this.state.count}
      </button>
    );
  }
}

Example

<!DOCTYPE html>
<html>
<head>
    <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body style="font-family:sans-serif;padding:20px;">
    <div id="root"></div>
    <script type="text/babel">
        class Timer extends React.Component {
            constructor(props) {
                super(props);
                this.state = { count: 0 };
            }
            componentDidMount() {
                this.timer = setInterval(() => this.setState(prev => ({ count: prev.count + 1 })), 1000);
            }
            componentWillUnmount() {
                clearInterval(this.timer);
            }
            render() {
                return <h3>Class Component Timer: {this.state.count}s</h3>;
            }
        }
        ReactDOM.createRoot(document.getElementById("root")).render(<Timer />);
    </script>
</body>
</html>
Try it Yourself >> Opens live sandboxed code editor
Advertisement
Google AdSense Slot (IN-ARTICLE)
Automated High-CTR Ad Rail • Set Publisher ID in config/adsense.php

Community Q&A & Discussion

No questions yet. Be the first to start the discussion!
Enterprise Operations Suite

Streamline Employee Payroll & Attendance Operations

Eliminate manual spreadsheet errors. Integrate automated attendance tracking, EPF/ESI statutory calculations, and custom GST invoices.

Copied!

AI Learning Assistant

Ready to explain & guide

Hello! I am your MBS Digital AI Tutor. Ask me to explain concepts, review code, or suggest debugging steps.

Quick Starters:
AI Tutor is thinking...