Class Based Components

Table of contents

No heading

No headings in the article.

Class-based components in React are JavaScript classes that extend the React.Component class and define a render() method that returns a React element.

In React, a class-based component is a type of component that is defined using the ES6 class syntax.

These components extend the React.Component class, and are used to create reusable, stateful components with their own internal logic and behaviour.

Class-based components are used to handle more complex components, such as components that require state management, event handling, and other advanced functionality.

Here's a simple example of a class-based component:

import React, { Component } from 'react';

class MyComponent extends Component {
  render() {
   a = 'Disha'
    return (
      <div>
        <h1>Hello,{this.a}</h1>
      </div>
    );
  }
}
export default MyComponent;

//output
Hello,Disha

In this example, the MyComponent class extends the Component class from React, and overrides the render() method to return a simple React element.

Class-based components have been used in React for a long time, but with the introduction of React Hooks in React 16.8, functional components are now the preferred way to write React components, as they are simpler and easier to read and maintain but class-based components are still used in some legacy code and may be necessary in certain situations where the use of hooks is not possible.