Building a Music Player App with React and Spotify API

In this tutorial, we will learn how to build a music player app using React and the Spotify API. React is a popular JavaScript library for building user interfaces, while the Spotify API allows us to access and interact with the Spotify music streaming service. By the end of this tutorial, you will have a fully functional music player app that can search for songs, retrieve user playlists, and control playback.

building music player app react spotify api

Introduction

What is React?

React is a JavaScript library for building user interfaces. It allows developers to create reusable UI components and efficiently update the UI in response to changes in data. React uses a virtual DOM (Document Object Model) to efficiently update only the parts of the UI that have changed, resulting in a fast and responsive user interface.

What is the Spotify API?

The Spotify API is a set of web APIs provided by Spotify that allows developers to access and interact with the Spotify music streaming service. With the Spotify API, we can search for songs, retrieve user playlists, control playback, and more. It provides a rich set of features for building music-related applications.

Setting Up the Project

To get started with building our music player app, we need to set up a new React project and install the necessary dependencies.

Creating a new React project

To create a new React project, we can use the create-react-app command-line tool. Open your terminal and run the following command:

npx create-react-app music-player-app

This command will create a new directory called music-player-app and set up a new React project inside it.

Installing necessary dependencies

Next, we need to install the necessary dependencies for our music player app. Change into the music-player-app directory and run the following command to install the spotify-web-api-js package:

npm install spotify-web-api-js

The spotify-web-api-js package is a JavaScript wrapper for the Spotify Web API that makes it easier to interact with the Spotify API in our React app.

Authenticating with Spotify

Before we can start using the Spotify API, we need to authenticate our app with Spotify and obtain client credentials.

Registering your app with Spotify

To register our app with Spotify, we need to create a new app in the Spotify Developer Dashboard. Follow these steps to register your app:

  1. Go to the Spotify Developer Dashboard and log in with your Spotify account.
  2. Click on the "Create an App" button.
  3. Fill in the required fields, such as the app name and app description.
  4. After creating the app, you will be taken to the app dashboard. Note down the "Client ID" and "Client Secret" values, as we will need them later for authentication.

Obtaining client credentials

To obtain client credentials for our app, we need to authenticate with Spotify using the client ID and client secret that we obtained in the previous step. We can use the spotify-web-api-js package to authenticate our app. Here's an example of how to authenticate with Spotify:

import SpotifyWebApi from 'spotify-web-api-js';

const spotifyApi = new SpotifyWebApi();
spotifyApi.setClientId('YOUR_CLIENT_ID');
spotifyApi.setClientSecret('YOUR_CLIENT_SECRET');
spotifyApi.setRedirectURI('http://localhost:3000/callback');

const scopes = ['user-read-private', 'user-read-email'];
const loginURL = spotifyApi.createAuthorizeURL(scopes);

In the code snippet above, we import the spotify-web-api-js package and create a new instance of the SpotifyWebApi class. We then set the client ID, client secret, and redirect URI using the setClientId, setClientSecret, and setRedirectURI methods, respectively. We also specify the required scopes and generate a login URL using the createAuthorizeURL method.

Building the User Interface

Now that we have set up our project and authenticated with Spotify, let's start building the user interface for our music player app.

Creating the main layout

The first step is to create the main layout for our app. We can use the react-router-dom package to handle routing in our app and create separate components for different pages. Here's an example of how to set up routing in our app:

import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import Home from './components/Home';
import Search from './components/Search';
import Playlist from './components/Playlist';

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/search" component={Search} />
        <Route path="/playlist/:id" component={Playlist} />
      </Switch>
    </Router>
  );
}

export default App;

In the code snippet above, we import the necessary components from the react-router-dom package and create separate components for the home page, search page, and playlist page. We then set up the routes using the Route component, specifying the path and component for each route.

Implementing the player controls

Next, let's implement the player controls for our music player app. We can use the spotify-web-api-js package to control playback and fetch data from Spotify. Here's an example of how to implement the player controls:

import React, { useEffect, useState } from 'react';
import SpotifyWebApi from 'spotify-web-api-js';

const spotifyApi = new SpotifyWebApi();

function PlayerControls() {
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTrack, setCurrentTrack] = useState(null);

  useEffect(() => {
    // Fetch the current playback state
    spotifyApi.getMyCurrentPlaybackState().then((response) => {
      setIsPlaying(response.is_playing);
      setCurrentTrack(response.item);
    });
  }, []);

  const handlePlay = () => {
    // Start playback
    spotifyApi.play();
    setIsPlaying(true);
  };

  const handlePause = () => {
    // Pause playback
    spotifyApi.pause();
    setIsPlaying(false);
  };

  return (
    <div>
      {currentTrack && (
        <div>
          <img src={currentTrack.album.images[0].url} alt={currentTrack.album.name} />
          <h3>{currentTrack.name}</h3>
          <p>{currentTrack.artists.map((artist) => artist.name).join(', ')}</p>
        </div>
      )}
      {isPlaying ? (
        <button onClick={handlePause}>Pause</button>
      ) : (
        <button onClick={handlePlay}>Play</button>
      )}
    </div>
  );
}

export default PlayerControls;

In the code snippet above, we import the necessary components from React and the spotify-web-api-js package. We create a functional component called PlayerControls that manages the playback state and current track. We use the useEffect hook to fetch the current playback state when the component is mounted, and update the state accordingly. We also define two event handlers, handlePlay and handlePause, that start and pause playback, respectively. Finally, we render the current track information and a button to control playback.

Fetching Data from Spotify

Now that we have built the user interface and implemented the player controls, let's fetch data from Spotify to populate our app.

Searching for songs

To search for songs, we can use the spotify-web-api-js package to make a request to the Spotify API. Here's an example of how to search for songs:

import React, { useState } from 'react';
import SpotifyWebApi from 'spotify-web-api-js';

const spotifyApi = new SpotifyWebApi();

function Search() {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);

  const handleSearch = () => {
    // Search for songs
    spotifyApi.searchTracks(query).then((response) => {
      setResults(response.tracks.items);
    });
  };

  return (
    <div>
      <input type="text" value={query} onChange={(e) => setQuery(e.target.value)} />
      <button onClick={handleSearch}>Search</button>
      <ul>
        {results.map((track) => (
          <li key={track.id}>{track.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default Search;

In the code snippet above, we create a functional component called Search that manages the search query and search results. We define an input field and a button to enter the search query and trigger the search. When the search button is clicked, we make a request to the Spotify API using the searchTracks method and update the search results state. Finally, we render the search results as a list of track names.

Retrieving user playlists

To retrieve user playlists, we can use the spotify-web-api-js package to make a request to the Spotify API. Here's an example of how to retrieve user playlists:

import React, { useEffect, useState } from 'react';
import SpotifyWebApi from 'spotify-web-api-js';

const spotifyApi = new SpotifyWebApi();

function Playlist() {
  const [playlists, setPlaylists] = useState([]);

  useEffect(() => {
    // Fetch user playlists
    spotifyApi.getUserPlaylists().then((response) => {
      setPlaylists(response.items);
    });
  }, []);

  return (
    <div>
      <ul>
        {playlists.map((playlist) => (
          <li key={playlist.id}>{playlist.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default Playlist;

In the code snippet above, we create a functional component called Playlist that manages the user playlists. We use the useEffect hook to fetch the user playlists when the component is mounted, and update the playlists state accordingly. Finally, we render the playlists as a list of playlist names.

Playing Music

Now that we can search for songs and retrieve user playlists, let's implement the functionality to play music in our app.

Handling playback events

To handle playback events, such as starting and pausing playback, we can use the spotify-web-api-js package to subscribe to playback events. Here's an example of how to handle playback events:

import React, { useEffect, useState } from 'react';
import SpotifyWebApi from 'spotify-web-api-js';

const spotifyApi = new SpotifyWebApi();

function PlayerControls() {
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTrack, setCurrentTrack] = useState(null);

  useEffect(() => {
    // Subscribe to playback events
    spotifyApi.subscribeToPlaybackState((state) => {
      setIsPlaying(state.isPlaying);
      setCurrentTrack(state.track);
    });
  }, []);

  // ...

  return (
    // ...
  );
}

export default PlayerControls;

In the code snippet above, we import the necessary components from React and the spotify-web-api-js package. We create a functional component called PlayerControls that manages the playback state and current track. We use the useEffect hook to subscribe to playback events when the component is mounted, and update the state accordingly. The subscribeToPlaybackState method takes a callback function that is called whenever a playback event occurs. We update the playback state and current track in the callback function.

Controlling playback state

To control the playback state, such as starting and pausing playback, we can use the spotify-web-api-js package to make requests to the Spotify API. Here's an example of how to control the playback state:

import React, { useEffect, useState } from 'react';
import SpotifyWebApi from 'spotify-web-api-js';

const spotifyApi = new SpotifyWebApi();

function PlayerControls() {
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTrack, setCurrentTrack] = useState(null);

  // ...

  const handlePlay = () => {
    // Start playback
    spotifyApi.play();
    setIsPlaying(true);
  };

  const handlePause = () => {
    // Pause playback
    spotifyApi.pause();
    setIsPlaying(false);
  };

  return (
    <div>
      {/* ... */}
      {isPlaying ? (
        <button onClick={handlePause}>Pause</button>
      ) : (
        <button onClick={handlePlay}>Play</button>
      )}
    </div>
  );
}

export default PlayerControls;

In the code snippet above, we define two event handlers, handlePlay and handlePause, that start and pause playback, respectively. We use the play and pause methods of the spotifyApi object to make requests to the Spotify API and control the playback state. We also update the playback state in the event handlers.

Conclusion

In this tutorial, we have learned how to build a music player app using React and the Spotify API. We started by setting up the project and authenticating with Spotify. Then, we built the user interface for our app and implemented the player controls. We also learned how to fetch data from Spotify, such as searching for songs and retrieving user playlists. Finally, we implemented the functionality to play music and control the playback state.

By following this tutorial, you should now have a good understanding of how to build a music player app with React and the Spotify API. You can further enhance your app by adding features like playlist management, audio visualization, and more. Happy coding!