How to build a live progress bar with React
You will need Node 6+ installed on your machine. Previous experience with React will be helpful.
Long running tasks are a feature of many web applications which need to be handled properly to improve the experience of the user. In many cases, a static progress bar that doesn’t update until the end is provided which leaves the user unsure of how long a task will take or if progress is being made at all.
We can improve this situation by making our progress bars show the actual progress of the task in realtime, and Pusher makes this really easy to do as you’ll see in the tutorial below.
Prerequisites
Previous experience with React is required to follow through with this tutorial. You also need to install Node.js (v6 and above) and npm on your machine if you don’t have them already. Installation instructions can be found here.
Getting started
Open a new terminal window and create a new folder called progress-bar
, then cd
into it:
mkdir progress-bar
cd progress-bar
Next, install create-react-app
, a tool that allows us to quickly get a React application up and running:
npm install -g create-react-app
Once create-react-app
is installed, use it to bootstrap a new React project. Run the command below within the progress-bar
directory.
create-react-app client
The above command will create a new directory called client
and install React as well as its accompanying dependencies. It may take a while to complete, so sit tight and wait. Once it’s done, you should see a some information in the terminal informing you of what you can do next.
Next, change into the newly created directory (cd client
)and run yarn start
to start the development server. Once the application compiles, you will be able to view it at http://localhost:3000.
Build the application frontend
For this demo, we will simulate the common task of uploading a large file to the server. We’re not going to upload a real file; however, we’ll write a small Node script that will simulate the effect of a file upload.
Let’s start by building the application frontend first. We need some additional dependencies for our React application, so let’s install them first. Within the client
directory, run the following command:
npm install pusher-js react-ladda
pusher-js
is the client side SDK for Channels, while react-ladda
lets us use the Ladda button library in our React app.
Open up App.js
in your favorite text editor and change its contents to look like this:
// client/src/App.js
import React, { Component } from 'react';
import LaddaButton, { XL, EXPAND_RIGHT } from 'react-ladda';
import Pusher from 'pusher-js';
import './App.css';
class App extends Component {
state = {
loading: false,
progress: 0,
};
componentDidMount() {
const pusher = new Pusher('<your app key>', {
cluster: '<your app cluster>',
encrypted: true,
});
const channel = pusher.subscribe('upload');
channel.bind('progress', data => {
this.setState({
progress: data.percent / 100,
});
if (data.percent === 100) {
this.setState({
loading: false,
progress: 0,
});
}
});
}
handleClick = event => {
event.preventDefault();
this.setState({
loading: !this.state.loading,
});
fetch('http://localhost:5000/upload', {
method: 'POST',
}).catch(error => console.log(error));
};
render() {
const { loading, progress } = this.state;
const message = loading ? (
<span className="progress-text">{progress * 100}% completed</span>
) : null;
return (
<div className="App">
<h1>Imaginary Image Upload Service :)</h1>
<LaddaButton
loading={this.state.loading}
onClick={this.handleClick}
progress={this.state.progress}
data-color="#eee"
data-size={XL}
data-style={EXPAND_RIGHT}
data-spinner-size={30}
data-spinner-color="#ddd"
data-spinner-lines={12}
>
Upload really large image!
</LaddaButton>
{message}
</div>
);
}
}
export default App;
Our React application consists of one button which, when clicked, will show the progress of the file upload. The componentDidMount()
lifecycle method houses the logic for streaming upload progress to the app in realtime.
We’re opening a connection to Channels using the subscribe()
method which allows us to subscribe to a new channel called upload
. Then, we listen for the progress
event on the upload
channel using the bind
method and update the application state once we receive a progress update.
Before you can integrate Channels into your application you need to sign up for a free account on Pusher. Once your account is created, select Channels apps on the sidebar, and hit Create Channels app to create a new app. Retrieve your credentials from the API Keys tab, and then replace the <your app key>
and <your app cluster>
placeholders in App.js
with the appropriate values.
Add the styles for the application
Let’s add the styles for the app’s frontend. Open up App.css
in your editor and replace its contents with the following styles:
// client/src/App.css
.App {
margin-top: 50px;
text-align: center;
}
.progress-text {
display: block;
font-size: 16px;
margin-top: 20px;
}
You also need to add the style for the Ladda button. You can do so by adding the following tag to the <head>
of the index.html
file within the client/public
directory:
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/Ladda/1.0.0/ladda.min.css">
At this point, the application should look like this:
Create the server component
We’ll set up the server in the next step so as to simulate the file upload and trigger upload progress updates from the server. Run the following command from the root of the progress-bar
directory to install the necessary dependencies:
npm install express cors dotenv pusher
Next, create a new file called server.js
in the root of your project directory and paste in the following code to set up a simple express server:
// server.js
require('dotenv').config({ path: 'variables.env' });
const express = require('express');
const cors = require('cors');
const Pusher = require('pusher');
const pusher = new Pusher({
appId: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_APP_KEY,
secret: process.env.PUSHER_APP_SECRET,
cluster: process.env.PUSHER_APP_CLUSTER,
encrypted: true,
});
const app = express();
app.use(cors());
app.set('port', process.env.PORT || 5000);
const server = app.listen(app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});
Create another file called variables.env
in the root of your project directory and change it’s contents to look like this:
// variables.env
PORT=5000
PUSHER_APP_ID=<your app id>
PUSHER_APP_KEY=<your app key>
PUSHER_APP_SECRET=<your app secret>
PUSHER_APP_CLUSTER=<your app cluster>
Remember, your Pusher credentials can be retrieved from the API Keys tab on the Pusher account dashboard.
Add the /upload route
If you check the handleClick()
method within App.js
, you will see that we are making a post request to /upload
when the button is clicked. Let’s go ahead and create this route within server.js
:
// server.js
...
app.use(cors());
app.post('/upload', (req, res) => {
let percent = 0;
const interval = setInterval(() => {
percent += 10;
pusher.trigger('upload', 'progress', {
percent,
});
if (percent === 100) clearInterval(interval);
}, 2000);
});
We’re simulating an upload progress of 10% every two seconds, and triggering a new update on check increment.
You can start the server by running node server.js
in a new terminal window and try out the application by clicking the upload button. You should see the progress update in realtime.
Conclusion
And that’s it! This is just scratching the surface of realtime updates using Pusher. Check out some other use cases for Channels, and as always, you can find the source code of this app in this GitHub repository.
24 October 2018
by Ayooluwa Isaiah