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 extends "Component" class.



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

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250