React Class Components are one of the building blocks of React, a popular JavaScript library for building user interfaces. Although functional components using hooks are the future of React, class components are still widely used and understanding them is important for working with older codebases or libraries.
Class components allow you to hold and manage local state and have lifecycle methods to handle side effects. A class component is defined by extending `React.Component`:
import React, { Component } from 'react';
class MyComponent extends Component {
render() {
return (
<div>
Hello, World!
</div>
);
}
}
export default MyComponent;
Class components often have a constructor where you can set up state and other instance properties. The state is where you store property values that belong to the component. When the state changes, the component re-renders.
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
}
Class components can also have methods to handle events and other actions. The state should not be modified directly but instead using the `this.setState()` method.
class Counter extends Component {
// ...constructor here...
handleIncrement = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={this.handleIncrement}>
Increment
</button>
</div>
);
}
}
Props are how components receive data from their parent components. Props are passed to the constructor and should be passed to the `super` method to make them available on `this.props`:
class Greeting extends Component {
constructor(props) {
super(props);
}
render() {
return {this.props.message};
}
}
Class components have several lifecycle methods that you can override to run code at particular times in the process:
class LifecycleComponent extends Component {
componentDidMount() {
console.log('Component Did Mount');
}
componentDidUpdate(prevProps, prevState) {
console.log('Component Did Update');
}
componentWillUnmount() {
console.log('Component Will Unmount');
}
render() {
return <div>LifeCycle Component</div>;
}
}
Below is a more detailed example of a class component that has state, props, event handling, and lifecycle methods:
import React, { Component } from 'react';
class UserProfile extends Component {
constructor(props) {
super(props);
this.state = {
userData: null,
error: null,
};
}
componentDidMount() {
const { userId } = this.props;
fetch(`https://api.example.com/users/${userId}`)
.then((response) => response.json())
.then(
(data) => this.setState({ userData: data }),
(error) => this.setState({ error })
);
}
handleButtonClick = () => {
console.log('Button Clicked!');
}
render() {
const { userData, error } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!userData) {
return <div>Loading...</div>;
} else {
return (
<div>
{userData.name}
<p>{userData.email}</p>
<button onClick={this.handleButtonClick}>
Click Me!
</button>
</div>
);
}
}
}
export default UserProfile;
React Class components serve as one of the foundational elements in learning React, even though the trend is leaning towards functional components and hooks. Class components provide you with a structured way to declare components with state, lifecycle methods, and other utilities that make them indispensable when dealing with complex logic and side effects, especially in older projects.
The aspects discussed in this guide, including the introduction to class components, constructors, state, props, lifecycle methods, and the comprehensive example, give you a rounded understanding of what class components are and how they operate within a React application. It is essential to understand the operational nuances and capabilities of class components to build robust and scalable applications using React.
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here