Understanding Class Components in React with Real Examples
React class components were the primary way of defining components before the introduction of functional components and hooks. Although functional components have become more popular, class components are still widely used in existing codebases. In this article, we'll explore the basics of class components and provide real-world examples to help you understand their usage.
Basics of Class Components
Class components are JavaScript classes that extend the React.Component class. They have a render method that defines what should be displayed on the screen. Unlike functional components, class components can hold and manage their own internal state using this.state. Let's create a simple class component to illustrate this:
// GreetUserClass.js import React, { Component } from 'react'; class GreetUserClass extends Component { constructor(props) { super(props); this.state = { greeting: 'Hello', }; } render() { return ( <div> <h1>{this.state.greeting}, {this.props.name}!</h1> </div> ); } } export default GreetUserClass;
In this example, GreetUserClass is a class component that has its own state (greeting). It takes a name prop and displays a greeting based on the internal state and the prop.
Managing State in Class Components
Class components can update their state using this.setState(). Let's extend our example to include a button that changes the greeting:
// GreetUserClass.js import React, { Component } from 'react'; class GreetUserClass extends Component { constructor(props) { super(props); this.state = { greeting: 'Hello', }; } changeGreeting = () => { this.setState({ greeting: 'Hola', }); }; render() { return ( <div> <h1>{this.state.greeting}, {this.props.name}!</h1> <button onClick={this.changeGreeting}>Change Greeting</button> </div> ); } } export default GreetUserClass;
// LifecycleLogger.js import React, { Component } from 'react'; class LifecycleLogger extends Component { componentDidMount() { console.log('Component is mounted.'); } componentDidUpdate() { console.log('Component is updated.'); } componentWillUnmount() { console.log('Component will unmount.'); } render() { return <p>Check console for lifecycle messages.</p>; } } export default LifecycleLogger;