React Class Components

React class components are one of the foundational ways to define components in React, especially before the introduction of hooks. They provide more features compared to functional components, such as state management and lifecycle methods.

1 Creating a Class Component

A class component is defined as an ES6 class that extends React.Component.

To create a class component in your program, we must import React, the React library required to use React-specific features like JSX and components, and Component which is a base class from React that allows us to create class-based components. The typical import statement to create a class component is give below.

</>
Copy
import React, { Component } from 'react';

Let us say that, we would like to create a class component named Welcome.

We create a class named Welcome, and this Welcome class extends the Component class from React, as shown in the following.

</>
Copy
class Welcome extends Component {

}

Here, Welcome is just the name of class component. You can rename this Welcome to any other name that you need, as per your requirements.

Once we define a React class component, the next thing we have to do is to include a render method, which returns the JSX to be rendered, as shown in the following example.

App.js

</>
Copy
import React, { Component } from 'react';

class Welcome extends Component {
  render() {
    return (
      <h2>Welcome to React Class Components!</h2>
    );
  }
}

export default Welcome;

Output: