React Class Components

In this tutorial, we will learn React Class Components with examples.

React Class Component Overview

  • Class components are ES6 classes that return JSX. 
  • Class components (ES6 class) extend the Component class in React. 
  • Naming convention: Class Components always start with a capital letter. 
  • Class Component takes Props (in the constructor) if needed Class component must have a render( ) method for returning JSX

React Class Component Example 1

In this example, we define a class component called Employee. It extends the Component class from the react package. The component has an initial state object with properties firstName, lastName, and email:
import React from "react"

class Employee extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            firstName: "Ramesh",
            lastName: "Fadatare",
            email: "ramesh@gmail.com"
        }
    }

    render(){
        return (
            <div className="center">
                <h1> Employee Details</h1> <hr />
                <p>{this.state.firstName}</p>
                <p>{this.state.lastName}</p>
                <p>{this.state.email}</p>
            </div>
        )
    }
}

export default Employee

Next, use this Employee class component in the App component:

import Greeting from './components/Employee'

function App() {

  return (
    <div>
        <Employee />
    </div>
  )
}

export default App

React Class Component Example 2

In this example, we define a class component called Counter. It extends the Component class from the react package. The component has an initial state with a count property set to 0. 
import React, { Component } from 'react';

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

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

  render() {
    return (
      <div>
        <h2>Count: {this.state.count}</h2>
        <button onClick={this.handleClick}>Increment</button>
      </div>
    );
  }
}

export default Counter;
Next, use this Counter class component in the App component:
import Greeting from './components/Counter'

function App() {

  return (
    <div>
        <Counter />
    </div>
  )
}

export default App
The handleClick method is defined as an arrow function within the class component. When the button is clicked, it calls this method to update the count state by incrementing it by 1 using setState(). 

The render() method is required in a class component and returns the JSX that defines the component's UI. It displays the current count value and a button to increment the count.

Comments