How to Create a Music Player App with React and Spotify API

In this tutorial, we will be creating a music player app using React and the Spotify API. The app will allow users to search for and play songs from Spotify’s extensive music library.

To get started, you will need the following prerequisites:
– Node.js and npm installed on your machine
– A Spotify developer account
– Basic knowledge of React

Let’s begin!

Step 1: Set Up the Project

First, create a new directory for your project and navigate to it in your terminal. Then, run the following command to set up a new React app:

npx create-react-app music-player

This will create a new directory named music-player with all the necessary files for a React app.

Next, navigate into the project directory:

cd music-player

Step 2: Create a Spotify Developer Account

To interact with the Spotify API, you will need to create a Spotify developer account and register a new application. Follow these steps:

  1. Visit the Spotify Developer Dashboard and log in with your Spotify account.
  2. Click on “Create an App” and fill in the required details. Make a note of the Client ID as we will need it later.
  3. Click on “Edit Settings” and add the following Redirect URIs:
    • `http://localhost:3000/callback`
    • `http://localhost:3000`
    • `http://localhost:3000/`
  4. Click on “Save” to save your changes.

Step 3: Set Up Authentication

To authenticate with the Spotify API, we will be using the Implicit Grant Flow. This flow allows us to authenticate without a server-side component.

First, let’s install the necessary packages:

npm install react-router-dom spotify-web-api-js

Now, create a new file named src/Auth.js and add the following code:

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

const Auth = () => {
  const [authenticated, setAuthenticated] = useState(false);
  const spotifyApi = new SpotifyWebApi();

  useEffect(() => {
    const params = getHashParams();
    const { access_token } = params;

    if (access_token) {
      spotifyApi.setAccessToken(access_token);
      setAuthenticated(true);
    }
  }, []);

  const getHashParams = () => {
    const hashParams = {};
    let e;
    const r = /([^&;=]+)=?([^&;]*)/g;
    const q = window.location.hash.substring(1);
    while ((e = r.exec(q))) {
      hashParams[e[1]] = decodeURIComponent(e[2]);
    }
    return hashParams;
  };

  return authenticated ? (
    <Redirect to="/dashboard" />
  ) : (
    <a
      className="btn-login"
      href={`https://accounts.spotify.com/authorize?client_id=${YOUR_CLIENT_ID}&response_type=token&redirect_uri=http://localhost:3000/callback&scope=user-read-private%20user-read-email`}
    >
      Login with Spotify
    </a>
  );
};

export default Auth;

Replace YOUR_CLIENT_ID with your Spotify application’s client ID.

Step 4: Create the Dashboard

Now, let’s create the dashboard component where users can search for and play songs. Create a new file named src/Dashboard.js and add the following code:

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

const spotifyApi = new SpotifyWebApi();

const Dashboard = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [searchResults, setSearchResults] = useState([]);

  const handleSearch = async () => {
    const { tracks } = await spotifyApi.searchTracks(searchTerm);
    setSearchResults(tracks.items);
  };

  const handlePlay = (uri) => {
    spotifyApi.play({ uris: [uri] });
  };

  return (
    <div>
      <h1>Music Player</h1>
      <input
        type="text"
        placeholder="Search for songs..."
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <button onClick={handleSearch}>Search</button>
      <ul>
        {searchResults.map((track) => (
          <li key={track.id}>
            {track.name} - {track.artists[0]?.name}
            <button onClick={() => handlePlay(track.uri)}>Play</button>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default Dashboard;

Step 5: Set Up Routes

Next, let’s set up the routes for our application. Open src/App.js and replace the contents with the following code:

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Auth from './Auth';
import Dashboard from './Dashboard';

const App = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/">
          <Auth />
        </Route>
        <Route path="/dashboard">
          <Dashboard />
        </Route>
      </Switch>
    </Router>
  );
};

export default App;

Step 6: Add Styling

To make our app look visually appealing, let’s add some basic styling. Create a new file named src/App.css and add the following code:

body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
}

h1 {
  text-align: center;
}

input {
  width: 100%;
  padding: 0.5rem;
  margin-bottom: 0.5rem;
}

.btn-login {
  display: block;
  margin: 2rem auto;
  padding: 0.5rem 1rem;
  background-color: #1db954;
  color: white;
  text-decoration: none;
  text-align: center;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  margin-bottom: 1rem;
}

button {
  padding: 0.25rem 0.5rem;
  background-color: #1db954;
  color: white;
  border: none;
  cursor: pointer;
}

Step 7: Finalize the App

Lastly, let’s make a few final adjustments before running the app.

Open src/index.js and replace the contents with the following code:

import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

Now, open src/index.css and remove its contents.

Step 8: Start the App

You’re ready to run the app! Start the development server by running the following command:

npm start

Open your web browser and navigate to `http://localhost:3000`. You should see a login button. Click on it to authenticate with Spotify and start using the music player app!

Conclusion

Congratulations! You have created a music player app with React and the Spotify API. You’ve learned how to set up authentication, search for songs, and play them using the Spotify API. You can now take this app further by adding features like playlists, album recommendations, and more.

Feel free to explore the possibilities of the Spotify API and expand on this project. Happy coding!

Related Post