Class-based Components
Simple App Using Class-based Component
Class based component is an alternative to functional component in react. Here, we use render() method  to process logic & display content. 
import React from "react"
// Class-based Component
class App extends React.Component {
    render() {
        return (
            <div>
                <h1>Hello World</h1>
            </div>
        )
    }
}
export default Appimport React from "react"
import ReactDOM from "react-dom"
import App from "./App"
ReactDOM.render(<App />, document.getElementById("root"))
<html>
    <head>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div id="root"></div>
        <script src="index.pack.js"></script>
    </body>
</html>We can place all the logic within render()method & display content in return()function.
import React from "react"
// Class-based Component
class App extends React.Component {
    render() {
        // Logic Goes Here
        const date = new Date()
        const hours = date.getHours()
        let timeOfDay
        
        if (hours < 12) {
            timeOfDay = "morning"
        } else if (hours >= 12 && hours < 17) {
            timeOfDay = "afternoon"
        } else {
            timeOfDay = "night"
        }
        
        // Display Output
        return (
            <h1>Good {timeOfDay} to you, sir or madam!</h1>
        )
    }
}
export default Appimport React from "react"
import ReactDOM from "react-dom"
import App from "./App"
ReactDOM.render(<App />, document.getElementById("root"))
<html>
    <head>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div id="root"></div>
        <script src="index.pack.js"></script>
    </body>
</html>Props in Class-based Component
InClassbased component this keyword should always precede props
import React, {Component} from "react"
import ReactDOM from "react-dom"
// App Component
class App extends React.Component {
    render() {
        return (
            <div>
                <Header username="John" />
            </div>
        )    
    }
}
// Header Component
class Header extends React.Component {
    render() {
        return (
            <header>
                // Using 'this' with 'props'
                <p>Welcome, {this.props.username}!</p>
            </header>
        )    
    }
}
ReactDOM.render(<App />, document.getElementById("root"))
<html>
    <head>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div id="root"></div>
        <script src="index.pack.js"></script>
    </body>
</html>Last updated
Was this helpful?