React - Class Components
Creating and using class components
Class components in React are ES6 classes that extend from React.Component
and can hold and manage their own state. They also provide lifecycle methods that can be used to run code at specific points in a component's lifecycle. This tutorial covers how to create and use class components in React.
Key Points:
- Class components are defined as ES6 classes that extend from
React.Component
. - Class components can manage their own state and use lifecycle methods.
- Class components are more feature-rich than functional components.
Defining a Class Component
To define a class component, create an ES6 class that extends from React.Component
and includes a render
method that returns JSX.
// Class component example
import React, { Component } from 'react';
class Welcome extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
export default Welcome;
In this example, the Welcome
component renders a greeting message using the name
prop.
Using Props in Class Components
Props are used to pass data from parent components to child components. In class components, props are accessed using this.props
.
// Using props in a class component
import React, { Component } from 'react';
class Welcome extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
export default Welcome;
// Using the Welcome component
import React from 'react';
import ReactDOM from 'react-dom';
import Welcome from './Welcome';
ReactDOM.render(<Welcome name="John" />, document.getElementById('root'));
Managing State in Class Components
State is a built-in object that allows class components to create and manage their own data. State is initialized in the constructor and updated using the setState
method.
// Using state in a class component
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}
export default Counter;
In this example, the Counter
component manages a count
state that is incremented each time the button is clicked.
Lifecycle Methods
Class components can define lifecycle methods to run code at specific points in a component's lifecycle, such as when the component mounts or updates.
// Using lifecycle methods in a class component
import React, { Component } from 'react';
class LifecycleDemo extends Component {
componentDidMount() {
console.log('Component did mount');
}
componentDidUpdate() {
console.log('Component did update');
}
componentWillUnmount() {
console.log('Component will unmount');
}
render() {
return <div>Lifecycle Demo</div>;
}
}
export default LifecycleDemo;
In this example, the LifecycleDemo
component logs messages to the console when it mounts, updates, and unmounts.
Binding Event Handlers
In class components, you often need to bind event handlers to the component instance to ensure the correct value of this
is used.
// Binding event handlers in a class component
import React, { Component } from 'react';
class Button extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('Button clicked', this);
}
render() {
return <button onClick={this.handleClick}>Click me</button>;
}
}
export default Button;
In this example, the handleClick
method is bound to the component instance in the constructor to ensure the correct value of this
.
Conditional Rendering
Class components can perform conditional rendering based on their state or props.
// Conditional rendering in a class component
import React, { Component } from 'react';
class Greeting extends Component {
constructor(props) {
super(props);
this.state = { isLoggedIn: false };
}
render() {
return (
<div>
{this.state.isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>}
<button onClick={() => this.setState({ isLoggedIn: !this.state.isLoggedIn })}>
{this.state.isLoggedIn ? 'Log Out' : 'Log In'}
</button>
</div>
);
}
}
export default Greeting;
In this example, the Greeting
component conditionally renders a message based on the isLoggedIn
state.
Summary
In this tutorial, you learned how to create and use class components in React. Class components are ES6 classes that extend from React.Component
and can manage their own state and lifecycle methods. You learned about defining class components, using props, managing state, using lifecycle methods, binding event handlers, and performing conditional rendering. Understanding class components is essential for building complex and interactive user interfaces in React.