Displaying an Album List with Class Components in React

Displaying an Album List with Class Components in React

While functional components are increasingly popular in React development for their simplicity and use of hooks, class components remain a vital part of React’s ecosystem, especially in legacy projects or when a more traditional OOP approach is preferred. In this tutorial, we’ll create a `AlbumList` class component that fetches and displays albums from the JSONPlaceholder API, a free fake online REST service.

Prerequisites

Before we begin, make sure you have:

  • Node.js and npm installed on your computer.
  • A new React project set up (using `create-react-app` is recommended).

Step 1: Setting Up the AlbumList Component

We’ll start by creating a class component that fetches data from an API and stores it in the component’s state.

Creating the Component

  1. Create a New File: In your project’s `src` folder, create a new file named `AlbumList.js`.
  2. Add the Component Code:
 
				
					import React, { Component } from 'react';

class AlbumList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            albums: [],
            isLoading: true,
            error: null
        };
    }

    componentDidMount() {
        fetch('https://jsonplaceholder.typicode.com/albums')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => this.setState({ albums: data, isLoading: false }))
            .catch(error => this.setState({ error: error.message, isLoading: false }));
    }

    render() {
        const { albums, isLoading, error } = this.state;
        if (isLoading) return <p>Loading...</p>;
        if (error) return <p>Error: {error}</p>;

        return (
            <div>
                <h1>Albums</h1>
                <ul>
                    {albums.map(album => (
                        <li key={album.id}>
                            {album.title}
                        </li>
                    ))}
                </ul>
            </div>
        );
    }
}

export default AlbumList;

				
			

Understanding the Code

  • Constructor and State: The constructor initializes the state with an empty albums array, `isLoading` to true, and error to null.
  • Component Lifecycle`componentDidMount` is a lifecycle method called after the component is mounted to the DOM. Here, we fetch the albums and update the state accordingly.
  • Rendering: The component renders the list of albums or appropriate messages based on the loading and error state.

Step 2: Integrating the AlbumList Component

To display the `AlbumList` component in your application:

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

function App() {
    return (
        <div className="App">
            <AlbumList />
        </div>
    );
}

export default App;

				
			

This blog demonstrates the power and versatility of class components in React for handling API data fetching, state management, and conditional rendering. Class components, with their lifecycle methods and state management capabilities, offer a structured approach for building complex React applications.

Overview

Leave a Reply

Your email address will not be published. Required fields are marked *

Enquire Now