HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

React Class

React Class Components

A React class component is a way to define a component using a JavaScript class.

Class components have been the traditional way of creating components in React before the introduction of hooks.

They can manage local state, handle lifecycle methods, and are still widely used in existing codebases.

Here's an example of a basic class component:

import React, { Component } from 'react';
class ClassComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
incrementCount = () => {
this.setState({ count: this.state.count + 1 });
};

render() {
return (
<div>
<h1>{this.props.title} </h1>
<p>{this.props.description} </p>
<p>Count: {this.state.count} </p>
<button onClick={this.incrementCount}>Increment </button>
</div>
);
}
}
export default ClassComponent;

In this example:

  • 'ClassComponent' extends 'React.Component', making it a class-based React component.
  • The 'constructor 'method is used to initialize the component's state.
  • 'incrementCount' is a method that updates the state when a button is clicked.
  • The 'render' method returns JSX to describe the structure of the component.
  • You can use this class component in other parts of your application by importing and rendering it:

    import React from 'react';
    import ClassComponent from './ClassComponent';

    const App = () => {
    return (
    <div>
    <ClassComponent title="Class Component" description="This is a class component." />
    </div>
    );
    };

    export default App;