08 Class Components - biswajitsundara/react GitHub Wiki

Class component is a java script class that holds a functionality.

  • Functional component is just a java script function that accepts props as an argument and returns JSX (react element)
  • Class component extends the React.Component class and has a render function that returns the JSX (react element)
  • Before React 16.8, only class component had the state, life cycle feature and the function components were considered state less.
  • However with the addition of hooks now functional components as powerful as class components.
  • All the new projects are using only functional components and there's no need to research further on class components.
  • However all the old projects still have class components and react still supports it.

Basic Example

import React from "react";

export class AppUser extends React.Component{

    render(){
        return <h1>Hello User</h1>;
    }
}

In App.js it's similar like how we call the functional components.

function App() {
  return <AppUser /> ;
}

Using Props

Let's say we want to pass the username to the class component

import React from "react";

export class AppUser extends React.Component{

    render(){
        const {username} = this.props;
        return <h1>Hello {username}</h1>;
    }
}
//App.js

function App() {
  return <AppUser username="Biswajit"/> ;
}

Using Constructor

We can't use this.props in constructor directly. We will have to make a super() call.

import React from "react";

export class AppUser extends React.Component{

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

    render(){
        const {username} = this.props;
        return <h1>Hello {username}</h1>;
    }
}
//App.js

function App() {
  return <AppUser username="Biswajit"/> ;
}

If we want to work with states, then in the constructor we can maintain this.state

⚠️ **GitHub.com Fallback** ⚠️