React Tutorial: Learn the Basics and Create a Real-World Web Application

React is the most popular front-end JavaScript library today. From startups to big corporations, companies are adopting this widely used technology. Big names like Netflix, Airbnb, The New York Times, and many more are already using it on their websites, as well as their mobile applications. React’s popularity grew mainly due to how fast React web applications perform when compared to those developed using Angular. React introduced several concepts that overcame the drawbacks of previous frontend frameworks. 

Master the fundamentals of React including JSX, props, state, and events. Consider the React.js Certification Training Course. Enroll now!

This article will help you get a grip on the basic concepts of React. First, we’ll go through some of the basic React concepts. Then, we will create our own music application called Musicophile. This application will enable us to search for songs, preview them, and then add them to our Spotify playlists. 

We will cover the following topics in this article:

  1. What is React?
  2. Features of React
  3. Components in React
  4. Props in React
  5. State in React
  6. Event handling in React
  7. Event binding in React
  8. Create a React application - Musicophile: 
    1. React Installation
    2. Initialize a React app
    3. Create components of the App
    4. Connect to Spotify using Web API
    5. Summary of the steps

9. Industry Trends

What is React?

React is a JavaScript library used for building fast and interactive user interfaces for the web, as well as mobile applications. It is an open-source, component-based front-end library responsible only for the view layer of the application. Jordan Walke, a software engineer at Facebook, created React. Facebook initially developed and maintained React, and it was later used in its products, like WhatsApp & Instagram. It is now the most popular front-end library for the web and mobile app development. In a model-view-controller (MVC) architecture, React is the view layer — responsible for how an app looks and feels.

model-view

Fig: React MVC Diagram

Now that we know what React is, let’s move on and look into React’s features.

Features of React

JSX - JavaScript Syntax Extension

JSX is a syntax extension of JavaScript. It is used with React to describe what the user interface should look like. By using JSX, we can write HTML structures in the same file that contains JavaScript code. This makes the code easier to understand and debug, as it eliminates the need for complex JavaScript DOM structures.

Virtual DOM

React keeps a lightweight representation of the real DOM in the memory, known as the virtual DOM. When the state of an object changes, virtual DOM changes only that object in the real DOM, rather than updating all the objects.

virtual-real-dom

Fig: Virtual DOM

Architecture

In a Model-View-Controller (MVC) architecture, React is the ‘View’ that is responsible for how the app looks and feels.

mvc

Fig: MVC architecture

One-way data binding

React’s one-way data binding keeps everything modular and fast. A unidirectional data flow means that when designing a React app, you often nest child components within parent components and you know where and when an error occurs, giving you better control of the entire web application.

data-binding

Fig: One-way data binding

Extensions

React goes beyond simple UI and has many extensions for complete application architecture support. It provides server-side rendering, which means rendering a normally client-side only web application on the server and then sending a fully rendered page to the client. It also leverages Flux and Redux extensively in web application development. React Native, a prevalent framework used to create cross-compatible mobile applications is also derived from React.

Debugging

React applications are extremely easy to test due to a large developer community. Facebook even provides a small browser extension that makes React debugging faster and easier.

react-extension

Fig: React extension

This extension adds a React tab in the developer tools option in the Chrome web browser so that React components can be inspected automatically.

Now let’s look into the most important concept of React: components.

Components in React

Components are the building blocks of any React application, and a single app usually consists of multiple components. A component is essentially a piece of the user interface. It splits the user interface into independent, reusable parts that can be processed separately.

facebook-components

Fig: Facebook components

Important aspects of components include: 

  • Re-usability

    A component used in one area of the application can be reused in another area. This helps speed up the development process. 
  • Nested components

    A component can contain several other components.
  • Render method

    In its minimal form, a component must define a render method that specifies how the component renders to the DOM.
  • Passing Props (Properties)

    A component can also receive props. These are properties that its parent passes to specify particular values.

There are two types of components in React:

react

Fig: React components

  • Functional components: These types of components have no state of their own and only contain a render method, and are also called stateless components. They may derive data from other components as props (properties).

function Greeting(props) {

  return <h1>Welcome to {props.name}</h1>;

}

  • Class components: These types of components can hold and manage their own state and have a separate render method to return JSX on the screen. They are also called stateful components as they can have a state.

class Greeting extends React.Component {

  render() {

    return <h1>Welcome to {this.props.name}</h1>;

  }

}

Now, let’s look into another very important concept in React called props.

Props in React

Props is short for Properties. It is a built-in object in React that stores the value of attributes of a tag and works like HTML attributes. It provides a way to pass data from one component to others. Props are passed to the component in the same way as arguments passed in a function. Unlike the state in React, props are immutable.

props

Fig: Props

Basically, props are used to pass data between components, but how do we store data from a single component? 

State in React

The state is a built-in React object used to contain data or information about the component. The state in a component can change over time and whenever it changes, the component rerenders. The change in state can happen as a response to user action or system-generated events. It determines the behavior of the component and how it will render. 

class Greetings extends React.Component {

  state = {

    name: "World"

  };

  updateName() {

    this.setState({ name: "Simplilearn" });

  }

  render() {

      return(

          <div>

              {this.state.name}

          </div>

      )

  }

}

Event Handling in React

Every application revolves around handling and listening to events in order to do something else in response. An event is an action that could be triggered as a result of the user action or system-generated event.

<button onClick={showMessage}> Click me! </button>

  • React events are named in camelCase rather than lowercase in plain HTML
  • In JSX, functions are passed as events, instead of strings like in HTML

Event Binding in React

Event binding tells the browser which function is called when a particular event occurs.

There are several ways to bind events in React:

  • Arrow functions in the render method

render() {

   return(<MyInput onChange={ (e) => this.handleOnChange(e) } />)

}

  • Binding the event handler in the constructor

class MyClass extends Component {

  constructor(props) {

    super(props)

    this.handleClick = this.handleClick.bind(this)

  }

}

Now that we know React’s most important concepts, let’s go ahead and create a full-fledged React web application.

Create a React Application: Musicophile

We are going to make our own Spotify-integrated application; we will call it Musicophile. This application will allow us to search for songs, preview them and then add those songs to our Spotify playlists. 

musicophile

Fig: Musicophile

React Installation

  • Install nodeJS on your computer if it is not already installed

node

We install nodeJS because the node package manager (npm) is used to create a React application and also because it can be used as a backend when creating a complete web application.

  • Install a text editor of your choice. We are using Visual Studio Code in this tutorial, but you can also use other editors, like Atom and Sublime Text if you are more comfortable with those.

code-editing

  • Install the create-react-app package using the command prompt in Windows, or Terminal if you have a Mac or Linux. We recommend using -g to install this package globally to avoid any issues when running the React application.

command-prompt

Now we have all the tools we need to create our first React application, so let’s begin by creating one.

Creating a React App

  • In CMD or Terminal, type this command to create a React app:

C:\Users\taha.sufiyan\Desktop>create-react-app musicophile

Here, the app is named ‘musicophile’, but you can change it to any name you’d prefer. This is just for naming the root directory of the project, which will be created as a result of this command. This action will take some time, and after it completes setting up the application, you’ll see this screen:

command-prompt2.

  • You can start the React application by going into the newly-created directory and starting the app. In this case, type cd musicophile and then type npm start to run the application.

commandpromt.

The development server will start running and a new tab will open in your web browser with the default React application screen. In case a new tab doesn’t open automatically, you can manually do so by going to http://localhost:3000/

learn-react

  • To stop the application, you have to press ctrl + C and then press Y to confirm

npm

Create Components of the App

As we know, everything is a component in React. Everything you see here are separate components that have been combined to create complete web applications. These are the components that we will be creating for this application:

  • App: This will act as a container for all the other components when they are combined, which will provide the complete application.
  • Search Bar: This will be used to search for songs, albums or artists in the Spotify database.
  • Search Results: This will display the results that the Spotify servers return. 
  • Track: Each track that Spotify returns will be a separate component. 
  • Track List: This will group all tracks into a single component.
  • Playlist:  This will be used to add the playlist to your Spotify account.

It is crucial to visualize a React application in terms of components before working on it.

Note: There is a lot of CSS styling going on here to achieve the desired design and for that, we have also added the CSS stylesheets that are used for each component, which you can then add to your project to get the exact same result. Later on, you may also tweak CSS styles to suit your own style. This will help you understand the CSS classes and design concepts used here.

musicophile2

Fig: Musicophile components

Let’s start with the development of Musicophile:

  • Open the project folder in the text editor, and, inside the src folder, create a components folder. This is where we will add all our components.

Development of Musicophile

1. Search Bar 

  1. Create a new folder, SearchBar, inside the components folder.
  2. Create a new component file, and name it as SearchBar.js
  3. Create a new CSS file for styling this component: SearchBar.css
  4. Add the following code in the JavaScript file: 
  1. import React from "react";
  2.  
  3. import "./SearchBar.css";
  4.  
  5. class SearchBar extends React.Component {
  6.   constructor(props) {
  7.     super(props);
  8.  
  9.     this.state = {
  10.       term: ""
  11.     };
  12.  
  13.     this.handleTermChange = this.handleTermChange.bind(this);
  14.     this.search = this.search.bind(this);
  15.     this.handleEnter = this.handleEnter.bind(this);
  16.   }
  17.  
  18.   handleTermChange(event) {
  19.     this.setState({ term: event.target.value });
  20.   }
  21.  
  22.   search() {
  23.     this.props.onSearch(this.state.term);
  24.   }
  25.  
  26.   handleEnter(event) {
  27.     if (event.keyCode === 13) {
  28.       this.search();
  29.     }
  30.   }
  31.  
  32.   render() {
  33.     return (
  34.       <div className="SearchBar">
  35.         <input
  36.           placeholder="Enter song, album or artist"
  37.           onChange={this.handleTermChange}
  38.           onKeyUp={this.handleEnter}
  39.         />
  40.         <button className="SearchButton" onClick={this.search}>
  41.           SEARCH
  42.         </button>
  43.       </div>
  44.     );
  45.   }
  46. }
  47.  
  48. export default SearchBar;
  49.  
  1. Import React (Line 1)
  2. Import CSS file to apply styling (Line 3)
  3. Define an initial state to store user input (Lines 9 – 11)
  4. Bind all the functions so they refer to the current component class (Lines 13 – 15)
  5. Functions are aptly named according to the tasks they perform:
    > handleTermChange: set state value to user input (Lines 18 – 20)
    > search: to search for the track inputted by the user (Lines 22 – 24)
    > handleEnter: to trigger search whenever user presses the Enter key (Lines 26 – 30)
    > render: render the search bar to the screen (Lines 32 – 46)
  6. Export the component (Line 48)

CSS Stylesheet - SearchBar.css

  1. .SearchBar {
  2.   display: flex;
  3.   flex-direction: column;
  4.   align-items: center;
  5.   padding-top: 6.94rem;
  6.   margin-bottom: 6.33rem;
  7. }
  8.  
  9. .SearchBar input {
  10.   width: 287px;
  11.   padding: 0.88rem 0;
  12.   border: 1px solid #fff;
  13.   border-radius: 3px;
  14.   margin-bottom: 2.22rem;
  15.   color: #010c3f;
  16.   text-align: center;
  17.   font-size: 1rem;
  18. }
  19.  
  20. .SearchBar input:focus {
  21.   outline: none;
  22. }
  23.  
  24. .SearchButton {
  25.   cursor: pointer;
  26.   width: 8.11rem;
  27.   padding: 0.77rem 0;
  28.   border-radius: 54px;
  29.   background-color: #1db954;
  30.   text-align: center;
  31.   font-family: "Montserrat", sans-serif;
  32.   font-size: 0.833rem;
  33.   transition: background-color 0.25s;
  34.   border: 0px;
  35.   color: #fff;
  36.   font-weight: 500;
  37. }
  38.  
  39. .SearchButton:hover {
  40.   background-color: rgba(65, 233, 129, 0.7);
  41. }

2.Track

  1. Create a new folder, Track, inside the components folder
  2. Create a new component file, and name it Track.js
  3. Create a new CSS file to style this component: Track.css
  4. Add the following code in the JavaScript file:
  1. import React from "react";
  2.  
  3. import "./Track.css";
  4.  
  5. class Track extends React.Component {
  6.   constructor(props) {
  7.     super(props);
  8.  
  9.     this.addTrack = this.addTrack.bind(this);
  10.     this.removeTrack = this.removeTrack.bind(this);
  11.   }
  12.  
  13.   addTrack(event) {
  14.     this.props.onAdd(this.props.track);
  15.   }
  16.  
  17.   removeTrack(event) {
  18.     this.props.onRemove(this.props.track);
  19.   }
  20.  
  21.   renderAction() {
  22.     if (this.props.isRemoval) {
  23.       return (
  24.         <button className="Track-action" onClick={this.removeTrack}>
  25.           -
  26.         </button>
  27.       );
  28.     }
  29.     return (
  30.       <button className="Track-action" onClick={this.addTrack}>
  31.         +
  32.       </button>
  33.     );
  34.   }
  35.  
  36.   render() {
  37.     return (
  38.       <div className="Track">
  39.         <div className="Track-information">
  40.           <h3>{this.props.track.name}</h3>
  41.           <p>
  42.             {this.props.track.artist} | {this.props.track.album}
  43.           </p>
  44.           <iframe
  45.             src={"https://open.spotify.com/embed/track/" + this.props.track.id}
  46.             width="300"
  47.             height="80"
  48.             frameborder="0"
  49.             allowtransparency="true"
  50.             allow="encrypted-media"
  51.             title="preview"
  52.           />
  53.         </div>
  54.         {this.renderAction()}
  55.       </div>
  56.     );
  57.   }
  58. }
  59.  
  60. export default Track;
  1. Import React (Line 1)
  2. Import CSS file to apply styling (Line 3)
  3. Bind all the functions so they refer to the current component class (Lines 9 – 10)
  4. Functions are aptly named according to the tasks they perform:
    > addTrack: to add the track to playlist (Lines 13 – 15)
    > removeTrack: to remove the track from playlist (Lines 17 – 19)
    > renderAction: render buttons for adding and removing tracks (Lines 21 – 34)
    > render: render track to the screen (Lines 36 – 57)
  5. Export the component (Line 60)

CSS Stylesheet - Track.css

  1. .Track {
  2.   display: flex;
  3.   align-items: center;
  4.   border-bottom: 1px solid rgba(256, 256, 256, 0.8);
  5. }
  6.  
  7. .Track-action {
  8.   cursor: pointer;
  9.   padding: 0.5rem;
  10.   font-size: 1.05rem;
  11.   transition: color 0.25s;
  12.   border: 0px;
  13.   background-color: rgba(0, 0, 0, 0);
  14.   color: #fff;
  15. }
  16.  
  17. .Track-action:hover {
  18.   color: rgba(265, 265, 265, 0.5);
  19. }
  20.  
  21. .Track-information {
  22.   flex-grow: 1;
  23.   display: flex;
  24.   flex-direction: column;
  25.   justify-content: center;
  26.   height: 180px;
  27. }
  28.  
  29. .Track-information h3 {
  30.   margin-bottom: 0.22rem;
  31. }
  32.  
  33. .Track-information p {
  34.   font-size: 0.83rem;
  35.   font-weight: 300;
  36.   color: rgba(256, 256, 256, 0.8);
  37. }
  38.  
  39. .Track-information iframe {
  40.   margin: 0.75rem;
  41. }
  42.  

3. Track List

  1. Create a new folder, TrackList, inside the components folder
  2. Create a new component file, and name it TrackList.js
  3. Create a new CSS file for styling this component: TrackList.css
  4. Add the following code in the JavaScript file: 
  1. import React from "react";
  2.  
  3. import "./TrackList.css";
  4.  
  5. import Track from "../Track/Track";
  6.  
  7. class TrackList extends React.Component {
  8.   render() {
  9.     return (
  10.       <div className="TrackList">
  11.         {this.props.tracks.map(track => {
  12.           return (
  13.             <Track
  14.               track={track}
  15.               key={track.id}
  16.               onAdd={this.props.onAdd}
  17.               isRemoval={this.props.isRemoval}
  18.               onRemove={this.props.onRemove}
  19.             />
  20.           );
  21.         })}
  22.       </div>
  23.     );
  24.   }
  25. }
  26.  
  27. export default TrackList;
  28.  
  1. Import React (Line 1)
  2. Import CSS file to apply styling (Line 2)
  3. Import Track component (Line 5)
  4. Functions are aptly named according to the tasks they perform:
    Render: to pass each track as props to the track component and add each track to the tracklist, then render. (Lines 8 – 24)
  5. Export the component. (Line 27)

CSS Stylesheet - TrackList.css

  1. .TrackList {
  2.   width: 100%;
  3. }

4. Search Results

  1. Create a new folder, SearchResults, inside the components folder
  2. Create a new component file, and name it as SearchResults.js
  3. Create a new CSS file to style this component: SearchResults.css
  4. Add the following code in the JavaScript file: 
  1. import React from "react";
  2.  
  3. import "./SearchResults.css";
  4.  
  5. import TrackList from "../TrackList/TrackList";
  6.  
  7. class SearchResults extends React.Component {
  8.   render() {
  9.     return (
  10.       <div className="SearchResults">
  11.         <h2>Results</h2>
  12.         <TrackList tracks={this.props.searchResults} onAdd={this.props.onAdd} />
  13.       </div>
  14.     );
  15.   }
  16. }
  17.  
  18. export default SearchResults;
  19.  
  1. Import React (Line 1)
  2. Import CSS file to apply style (Line 3)
  3. Import TrackList component (Line 5)
  4. Functions are aptly named according to the tasks they perform:
    Render: to render the search results to the screen. (Lines 8 – 15)
  5. Export the component. (Line 18)

CSS Stylesheet - SearchResults.css

  1. .SearchResults {
  2.   width: 50%;
  3.   height: 950px;
  4.   overflow-y: scroll;
  5.   padding: 0.88rem;
  6.   background-color: rgba(95, 23, 23, 0.7);
  7.   box-shadow: 0 4px 2px 2px #000000;
  8. }
  9.  
  10. ::-webkit-scrollbar {
  11.   width: 0px;
  12.   background: transparent;
  13. }
  14.  
  15. @media only screen and (max-width: 1020px) {
  16.   .SearchResults {
  17.     width: 90%;
  18.     margin-bottom: 2rem;
  19.   }
  20. }
  21.  

5. Playlist

  1. Create a new folder, Playlist, inside the components folder
  2. Create a new component file, and name it as Playlist.js
  3. Create a new CSS file for styling this component: Playlist.css
  4. Add the following code in the JavaScript file: 
  1. import React from 'react';
  2.  
  3. import './Playlist.css';
  4.  
  5. import TrackList from '../TrackList/TrackList';
  6.  
  7. class Playlist extends React.Component {
  8.   constructor(props) {
  9.     super(props);
  10.  
  11.     this.handleNameChange = this.handleNameChange.bind(this);
  12.   }
  13.  
  14.   handleNameChange(event) {
  15.     this.props.onNameChange(event.target.value);
  16.   }
  17.  
  18.   render() {
  19.     return (
  20.       <div className="Playlist">
  21.         <input onChange={this.handleNameChange} defaultValue={'New Playlist'} />
  22.         <TrackList tracks={this.props.playlistTracks}
  23.                    isRemoval={true}
  24.                    onRemove={this.props.onRemove} />
  25.         <button className="Playlist-save" onClick={this.props.onSave}>SAVE TO SPOTIFY</button>
  26.       </div>
  27.     );
  28.   }
  29. }
  30.  
  31. export default Playlist;
  1. Import React (Line 1)
  2. Import CSS file to apply style (Line 3)
  3. Import TrackList component (Line 5)
  4. Bind all the functions so they refer to the current component class (Line 11)
  5. Functions are aptly named according to the tasks they perform:
    > handleNameChange: to change the name of playlist. (Lines 14 – 16)
    > render: to render the playlist to the screen. (Lines 18 – 28)
  6. Export the component. (Line 31)

CSS Stylesheet - Playlist.css

  1. .Playlist {
  2.   display: flex;
  3.   flex-direction: column;
  4.   align-items: center;
  5.   overflow-y: scroll;
  6.   width: 37%;
  7.   max-height: 950px;
  8.   padding: 2.27rem 1.16rem;
  9.   background-color: rgba(95, 23, 23, 0.7);
  10.   box-shadow: 0 4px 2px 2px #000000;
  11. }
  12.  
  13. .Playlist input {
  14.   width: 100%;
  15.   border: 0;
  16.   outline: 0;
  17.   background: transparent;
  18.   border-bottom: 1px solid #6f6f6f;
  19.   font-family: "Montserrat", sans-serif;
  20.   font-size: 1.55rem;
  21.   color: #fff;
  22. }
  23.  
  24. .Playlist-save {
  25.   cursor: pointer;
  26.   width: 10rem;
  27.   padding: 0.77rem 0;
  28.   border-radius: 54px;
  29.   border-width: 0px;
  30.   margin-top: 1.27rem;
  31.   background-color: #1db954;
  32.   text-align: center;
  33.   font-family: "Montserrat", sans-serif;
  34.   font-size: 0.83rem;
  35.   transition: background-color 0.25s;
  36.   color: #fff;
  37.   font-weight: 500;
  38. }
  39.  
  40. .Playlist-save:hover {
  41.   background-color: rgba(65, 233, 129, 0.7);
  42. }
  43.  
  44. ::-webkit-scrollbar {
  45.   width: 0px;
  46.   background: transparent;
  47. }
  48.  
  49. @media only screen and (max-width: 1020px) {
  50.   .Playlist {
  51.     width: 90%;
  52.   }
  53. }
  54.  

6. App

  1. Create a new folder, App, inside the components folder
  2. Move App.js and App.css inside this folder
  3. Replace the code in App.js with the following code: 
  1. import React from "react";
  2. import "./App.css";
  3.  
  4. import Playlist from "../Playlist/Playlist";
  5. import SearchBar from "../SearchBar/SearchBar";
  6. import SearchResults from "../SearchResults/SearchResults";
  7. import Spotify from "../../util/Spotify";
  8.  
  9. class App extends React.Component {
  10.   constructor(props) {
  11.     super(props);
  12.  
  13.     this.state = {
  14.       searchResults: [],
  15.       playlistName: "New Playlist",
  16.       playlistTracks: []
  17.     };
  18.  
  19.     this.search = this.search.bind(this);
  20.     this.addTrack = this.addTrack.bind(this);
  21.     this.removeTrack = this.removeTrack.bind(this);
  22.     this.updatePlaylistName = this.updatePlaylistName.bind(this);
  23.     this.savePlaylist = this.savePlaylist.bind(this);
  24.     this.removeTrackSearch = this.removeTrackSearch.bind(this);
  25.     this.doThese = this.doThese.bind(this);
  26.   }
  27.  
  28.   search(term) {
  29.     Spotify.search(term).then(searchResults => {
  30.       this.setState({ searchResults: searchResults });
  31.     });
  32.   }
  33.  
  34.   addTrack(track) {
  35.     let tracks = this.state.playlistTracks;
  36.     if (tracks.find(savedTrack => savedTrack.id === track.id)) {
  37.       return;
  38.     }
  39.  
  40.     tracks.push(track);
  41.     this.setState({ playlistTracks: tracks });
  42.   }
  43.  
  44.   removeTrack(track) {
  45.     let tracks = this.state.playlistTracks;
  46.     let trackSearch = this.state.searchResults;
  47.     tracks = tracks.filter(currentTrack => currentTrack.id !== track.id);
  48.     trackSearch.unshift(track);
  49.     this.setState({ playlistTracks: tracks });
  50.   }
  51.  
  52.   removeTrackSearch(track) {
  53.     let tracks = this.state.searchResults;
  54.     tracks = tracks.filter(currentTrack => currentTrack.id !== track.id);
  55.     this.setState({ searchResults: tracks });
  56.   }
  57.  
  58.   doThese(track) {
  59.     this.addTrack(track);
  60.     this.removeTrackSearch(track);
  61.   }
  62.  
  63.   updatePlaylistName(name) {
  64.     this.setState({ playlistName: name });
  65.   }
  66.  
  67.   savePlaylist() {
  68.     const trackUris = this.state.playlistTracks.map(track => track.uri);
  69.     Spotify.savePlaylist(this.state.playlistName, trackUris).then(() => {
  70.       this.setState({
  71.         playlistName: "New Playlist",
  72.         playlistTracks: []
  73.       });
  74.     });
  75.   }
  76.  
  77.   render() {
  78.     return (
  79.       <div>
  80.         <h1>
  81.           <a href="http://localhost:3000">Musicophile</a>
  82.         </h1>
  83.         <div className="App">
  84.           <SearchBar onSearch={this.search} />
  85.           <div className="App-playlist">
  86.             <SearchResults
  87.               searchResults={this.state.searchResults}
  88.               onAdd={this.doThese}
  89.             />
  90.             <Playlist
  91.               playlistTracks={this.state.playlistTracks}
  92.               onNameChange={this.updatePlaylistName}
  93.               onRemove={this.removeTrack}
  94.               onSave={this.savePlaylist}
  95.             />
  96.           </div>
  97.         </div>
  98.       </div>
  99.     );
  100.   }
  101. }
  102.  
  103. export default App;
  104.  
  1. Import React (Line 1)
  2. Import CSS file to apply style (Line 2)
  3. Import the following components of the project into the app component: (Lines 4 – 7)
    > PlayList
    > SearchBar 
    > SearchResults
    > Spotify
  4. Define initial states in the constructor for the data to be rendered (Lines 13 – 16)
  5. Bind all the functions in this component so they refer to the current component class (Lines 19 – 25)
  6. Functions are aptly named according to the tasks they perform:
    Search: to search for the track in Spotify (Lines 28 – 32)
    addTrack: to add a track to the playlist (Lines 34 – 42)
    removeTrack: to remove a track from the playlist (Lines 44 – 50)
    removeTrackSearch: to remove a track from the search results (Lines 52 – 56)
    doThese: on adding a track to playlist, remove that from search results (Lines 58 – 61)
    updatePlaylistName: to update the name of playlist (Lines 63 – 65)
    savePlaylist: to save the playlist into Spotify account (Lines 67 – 75)
    render: render the output to the screen (Lines 77 – 101) 
  7. Export the component (Line 103)

CSS Stylesheet - App.css

  1. body,
  2. html,
  3. #root {
  4.   height: 100%;
  5. }
  6.  
  7. html {
  8.   font-size: 18px;
  9. }
  10.  
  11. h1 {
  12.   padding: 0.77rem 0;
  13.   background-color: #b16d22;
  14.   text-align: center;
  15.   font-family: "Montserrat", sans-serif;
  16.   font-size: 1.88rem;
  17.   color: #fff;
  18. }
  19.  
  20. h1 .highlight {
  21.   color: rgb(46, 113, 238);
  22. }
  23.  
  24. a {
  25.   text-decoration: none;
  26.   color: #fff;
  27. }
  28.  
  29. h2 {
  30.   font-family: "Montserrat", sans-serif;
  31.   font-size: 1.55rem;
  32. }
  33.  
  34. .App {
  35.   height: 100%;
  36.   padding: 0 17% 10% 17%;
  37.   background-image: url("./bg1.jpg");
  38.   background-size: cover;
  39.   background-position: center;
  40.   background-repeat: no-repeat;
  41.   font-family: "Montserrat", sans-serif;
  42.   font-weight: 500;
  43.   color: #fff;
  44. }
  45.  
  46. .App-playlist {
  47.   display: flex;
  48.   justify-content: space-between;
  49.   width: 100%;
  50. }
  51.  
  52. @media only screen and (max-width: 1020px) {
  53.   .App-playlist {
  54.     align-items: center;
  55.     flex-direction: column;
  56.   }
  57. }

We have now created all the components — this is how your project structure should look in the text editor. Next, we will connect the application to Spotify.

spotify 

Connect to Spotify Using the API

1. Go to https://developer.spotify.com/dashboard/login and login with your Spotify account or sign up if you don’t have one.

dashboard

dashboard-2

2. Create a new app and enter the details in the dialog box and submit

dasboard3.

3. You’ll get a client ID, which we’ll use to connect our app to Spotify

no-data

 4. Add Redirect URI in the application settings, which in our case is http://localhost:3000

redirect-url

5. Now you’re ready to connect Musicophile to Spotify

Spotify.js

  • In the project folder located in the text editor and inside the src folder, create a util folder inside, where we will create a Spotify.js file

Creating Spotify.Js file

  • Inside the Spotify.js file, add the following code:
    1. const clientId = "4feb600fbe1e4dfeb6489e7e789de6d5"; // Have to replace it with your clientId
    2. const redirectUri = "http://localhost:3000/"; // Have to add this to your accepted Spotify redirect URIs on the Spotify API.
    3. let accessToken;
    4.  
    5. const Spotify = {
    6.   getAccessToken() {
    7.     if (accessToken) {
    8.       return accessToken;
    9.     }
    10.  
    11.     const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
    12.     const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);
    13.     if (accessTokenMatch && expiresInMatch) {
    14.       accessToken = accessTokenMatch[1];
    15.       const expiresIn = Number(expiresInMatch[1]);
    16.       window.setTimeout(() => (accessToken = ""), expiresIn * 1000);
    17.       window.history.pushState("Access Token", null, "/"); // This clears the parameters, allowing us to get a new access token when it expires.
    18.       return accessToken;
    19.     } else {
    20.       const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`;
    21.       window.location = accessUrl;
    22.     }
    23.   },
    24.  
    25.   search(term) {
    26.     const accessToken = Spotify.getAccessToken();
    27.     return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
    28.       headers: {
    29.         Authorization: `Bearer ${accessToken}`
    30.       }
    31.     })
    32.       .then(response => {
    33.         return response.json();
    34.       })
    35.       .then(jsonResponse => {
    36.         if (!jsonResponse.tracks) {
    37.           return [];
    38.         }
    39.         return jsonResponse.tracks.items.map(track => ({
    40.           id: track.id,
    41.           name: track.name,
    42.           artist: track.artists[0].name,
    43.           album: track.album.name,
    44.           uri: track.uri
    45.         }));
    46.       });
    47.   },
    48.  
    49.   savePlaylist(name, trackUris) {
    50.     if (!name || !trackUris.length) {
    51.       return;
    52.     }
    53.  
    54.     const accessToken = Spotify.getAccessToken();
    55.     const headers = { Authorization: `Bearer ${accessToken}` };
    56.     let userId;
    57.  
    58.     return fetch("https://api.spotify.com/v1/me", { headers: headers })
    59.       .then(response => response.json())
    60.       .then(jsonResponse => {
    61.         userId = jsonResponse.id;
    62.         return fetch(`https://api.spotify.com/v1/users/${userId}/playlists`, {
    63.           headers: headers,
    64.           method: "POST",
    65.           body: JSON.stringify({ name: name })
    66.         })
    67.           .then(response => response.json())
    68.           .then(jsonResponse => {
    69.             const playlistId = jsonResponse.id;
    70.             return fetch(
    71.               `https://api.spotify.com/v1/users/${userId}/playlists/${playlistId}/tracks`,
    72.               {
    73.                 headers: headers,
    74.                 method: "POST",
    75.                 body: JSON.stringify({ uris: trackUris })
    76.               }
    77.             );
    78.           });
    79.       });
    80.   }
    81. };
    82.  
    83. export default Spotify;
    1. ClientID obtained from the Spotify Web App (Line 1)
    2. redirectUri is the URL of your application (Line 2)
    3. getAccessToken: 
      > Checks if the user is logged in and returns if the access token is found (Lines 7 -9)
      > Enables us to get a new access token when it expires (Lines 11 – 18)   
      > Presents the user with a sign-in page and performs authorization using client ID to check if the ClientID is associated with that account (Lines 19 – 22)
    4. search: 
      > Fetches the requested track, while providing the required authorization (Lines 26 – 30)   
      > Converts the response received to JSON format (Lines 32 – 34)   
      > Returns empty if the response does not contain any tracks (Lines 36 – 38)   
      > Returns all the tracks with the associated parameters (Lines 39 – 45)
    5. savePlayList:
      > Checks whether the playlist has a name and if any track is added to the playlist (Lines 50 – 51)   
      > Authorization is done using accessToken (Lines 54 – 55)   
      > Retrieve the user’s playlists URL and adds a new playlist with specified name and tracks in it (Lines 58 – 79)
    6. Export the component (Line 83)

    The development of the Musicophile web application is now complete. 

    Summary of the Steps:

    1. Install React on the computer
    2. Create a React app
    3. Visualize the application in terms of components and then maintain the project structure accordingly in the text editor
    4. Add all the components to the project
    5. Add CSS to style all the components as required
    6. Go to Spotify developers’ dashboard and register Musicophile in your account
    7. Connect Musicophile to Spotify using Web API and Client ID
    8. Enjoy the results and feel free to tweak the design and functionality as you wish

    Musicophile Illustration

    Fig: Musicophile illustration

    We have created a complete React web application that is significant enough to be considered a real-world project. Now, let’s look into some industry trends.

    Industry Trends

    React is now the latest “must-have” tool for front-end development.

    • React developers earn more money when compared to other web development technologies. Due to the fast rendering of React applications, more and more companies are adopting this framework which has led to high demand for React developers all around the globe.

    average-sal-payscale

    The average salary for a React developer across the U.S. is $91,000 per year.

    source-payscale

    The average salary for a React developer in India is ₹7,25,000 per year.

    • React has been gaining popularity since it was released — and, it doesn’t seem to be slowing down, as the Google Trends chart indicates below. Facebook continues to add features to React that make it more powerful, too. Simply put, it’s safe to assume that React is here to stay.

    google-trends

    We have now created a fully functional, real-world React web application that works and looks great. We hope you were able to follow all the instructions with ease. In case you have any questions, feel free to use our comments section and we will be more than happy to help. Also, here is a playlist on YouTube that covers all concepts of React in depth.

    For more in-depth training on this increasingly popular web and mobile application development framework, enroll in Simplilearn’s React.js Training course today.

    About the Author

    Taha SufiyanTaha Sufiyan

    Taha is a Research Analyst at Simplilearn. He is passionate about building great user interfaces and keeps himself updated on the world of Artificial Intelligence. Taha is also interested in gaming and photography.

    View More
    • Disclaimer
    • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.