Articles → REACT.JS → Class And Function Components In React

Class And Function Components In React






What Are Class Components?






import React, { Component } from 'react';
import ReactDOM from 'react-dom'



class Message extends Component {

    fruits = ['Banana', 'orange', 'Apple'];
    render() {
        return (
            <h1>I am a class component demo</h1>
        );
    }

}

ReactDOM.render(<Message />, document.getElementById('root'));


Picture showing the output of class component in react.js
Click to Enlarge


What Are Function Components?






import React, { Component } from 'react';
import ReactDOM from 'react-dom'

function Fruits() {
    return <h2>Hi, I am a fruit!</h2>;
}

ReactDOM.render(<Fruits/>, document.getElementById('root'));


Picture showing the output of function component in react.js
Click to Enlarge


Difference




  1. Class component returns HTML using the render method
  2. Class components may contain variables and functions
  3. Class components extend the Component class



Posted By  -  Karan Gupta
 
Posted On  -  Thursday, August 5, 2021

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250