React Custom Reading Progress Bar Component Tutorial

Reading progress bar indicators are mostly seen on blogs as well as social reading sites. The reading progress bar provides the ideal way to motivate your site visitors to scroll through the whole web page to read your site’s content continually.

In this guide, we will share how to create a Reading Progress Bar in React js application using React Hooks and styled-components.

Its name says it all. A reading progress bar indicator is a graphical control element that gives your users a clear and concise idea about how much content they have gone through or how much post or article is left to be finished.

To build the reading progress bar component in React. We’ll create dummy blog content and insert some data into the blog component. Then, create another reading bar component and add the reading bar indicator at the top section of the web page.

As the user scrolls down, the reading bar will start filling the space horizontally and display user about the content reading progress.

Create New React App

To create a brand new React app, you need to run the following command.

npx create-react-app my-react-app

After the app is created; step inside the project folder.

cd my-react-app

Install NPM Dependencies

The bootstrap library is used to create the layout of the page; however it is utterly optional to install this library.

npm install bootstrap

We will be styling the progress bar component using the styled components package.

npm install styled-components

Create Blog Component

Next, you have to create the features/Blog.js file. In this file we will be setting the dummy content. As the user starts scrolling, this page will invoke the reading indicator.

import React from "react";

function Blog() {
  return (
    <div>
      <h2>React Reading Progress Bar Indicator Example</h2>
      <p>
        Velit class laoreet sem cursus ridiculus sociosqu mattis aliquam est.
        Per eget facilisi interdum curae curabitur. Sagittis aliquet sit dictum
        id ornare senectus rutrum. Porta turpis mollis laoreet curae bibendum.
        Porttitor velit libero aliquet semper suspendisse montes maximus risus a
        aenean. Finibus bibendum mi dignissim lacus dictum eu pharetra
        consectetur. Pharetra fames facilisi fusce ullamcorper litora rhoncus.
      </p>

      <p>
        Tincidunt orci fusce accumsan risus luctus nibh. Mi iaculis dolor eros
        fringilla platea lacinia natoque. Molestie mattis hendrerit luctus
        quisque venenatis congue nibh aenean sollicitudin. Porttitor interdum
        maximus primis pede quisque.
      </p>

      <p>
        Eleifend egestas nisl nostra vestibulum finibus tincidunt sagittis
        tellus imperdiet. Suspendisse suscipit amet nullam luctus aenean
        ultricies. Per sociosqu sollicitudin torquent vehicula at. Litora
        egestas montes enim ante imperdiet feugiat orci et aenean nec praesent.
        Ex turpis blandit ut luctus dignissim. Felis ut ad dignissim eros eu
        ullamcorper mollis lobortis.
      </p>

      <p>
        Hac tempor lobortis consectetur consectetuer suspendisse fames netus ex.
        Conubia commodo rutrum augue habitant sagittis amet lorem praesent
        integer fusce vehicula. Aenean curae tellus a accumsan mus magnis tempus
        maecenas ipsum dui aliquet. Leo ad commodo nostra eget fringilla
        fermentum. Mauris lobortis tristique fermentum ridiculus mus finibus id
        fringilla donec mi. Tortor praesent amet metus scelerisque at mus vitae
        facilisi tincidunt sem. Montes felis praesent aenean suspendisse orci
        nisi. Vulputate nam velit etiam placerat porttitor interdum consectetur
        nisi primis convallis.
      </p>

      <p>
        Arcu sagittis penatibus ac si senectus class conubia ut. Egestas si ante
        lacinia magnis porta vel diam volutpat odio. Nostra penatibus volutpat
        tristique sed tortor donec. Quis arcu ultricies eleifend eu convallis
        quisque pharetra elementum justo per imperdiet. Quis eget cursus erat
        sagittis tortor odio finibus at nullam. Lacinia gravida condimentum
        neque nulla maecenas taciti hendrerit dignissim dolor. Ante eleifend
        finibus tellus nunc feugiat commodo quis vitae.
      </p>

      <p>
        Vestibulum mollis lacus urna non porttitor dolor egestas cras. Ac aenean
        egestas si quisque facilisis sed velit fames aptent. Arcu sapien et
        blandit nam lorem duis si tortor. Ad convallis consectetur nulla diam
        parturient mattis et. Fusce pharetra nulla consectetuer nec sem pulvinar
        duis nisi luctus cursus. Senectus urna sed aptent ut amet ipsum rhoncus
        erat. Ornare vehicula tristique et nulla ligula tincidunt nisl.
      </p>

      <p>
        Quisque ad imperdiet vulputate eros mattis porta efficitur elementum
        malesuada. Sollicitudin aliquam luctus et congue porttitor nullam.
        Hendrerit cubilia porta mollis vel elementum sed proin lobortis
        pulvinar. Si cubilia aliquam convallis letius euismod nascetur faucibus.
        Ultricies per dictumst neque fames curabitur morbi venenatis dictum ante
        aenean libero.
      </p>

      <p>
        Letius pulvinar ac purus taciti sed. Finibus pulvinar congue eu
        parturient platea fames nullam sem. Risus in eu rutrum augue maximus
        nunc aliquam aliquet. Morbi lectus neque habitant quisque nullam purus
        vel bibendum enim at.
      </p>

      <p>
        Aliquet class est sem parturient senectus blandit mollis fringilla
        feugiat aliquam sociosqu. Facilisis magnis eget hendrerit ornare nulla.
        Lorem porttitor accumsan ante fames donec molestie fusce mus ac interdum
        placerat. Sollicitudin platea aenean urna luctus metus dis non laoreet
        facilisi pulvinar diam.
      </p>

      <p>
        Urna diam rhoncus augue nisl curae nibh primis in facilisis. Odio
        condimentum laoreet nam cursus ultricies. Sed dapibus auctor mus congue
        natoque faucibus amet tempus. Elit arcu congue tristique est pede
        tincidunt ad ac letius lectus. Scelerisque rutrum efficitur urna fusce
        semper leo litora curabitur. Semper mattis quisque maecenas urna class
        finibus nostra litora fermentum. Cras efficitur tincidunt adipiscing
        senectus fusce habitant. Ultricies diam himenaeos aliquet orci
        adipiscing ligula.
      </p>
    </div>
  );
}

export default Blog;

Create Reading Bar Indicator in React

Next, you have to create the features/ReadingProgressBar.js file and insert the following code within the file.

In this file we will be adding reading indicator. To add a reading progress bar in React, we will use useEffect and useState hooks.

We will calculate the page height and subtract the client height from the total height of the content page. The useState hook will be used to set the width of the react reading progress bar.

Whereas the useEffect hook performs the side effect every time a reading bar component renders.

import { React, useState, useEffect } from "react";
import styled from "styled-components";

const BarReading = styled.div`
  position: fixed;
  text-align: center;
  color: white;
  top: 0;
  left: 0;
  padding: 10px 0;
  background: #8e2de2;
  background: -webkit-linear-gradient(to right, #4a00e0, #8e2de2);
  background: linear-gradient(to right, #4a00e0, #8e2de2);
`;

function ReadingProgressBar() {
  const [barWidth, setBarWidth] = useState(0);

  const ScrollPosition = () => {
    var el = document.documentElement,
      ScrollPosTop = el.scrollTop || document.body.scrollTop,
      ScrollPosHeight = el.scrollHeight || document.body.scrollHeight;
    var percentage = (ScrollPosTop / (ScrollPosHeight - el.clientHeight)) * 100;

    setBarWidth(percentage);
  };

  useEffect(() => {
    window.addEventListener("scroll", ScrollPosition);
    return () => window.removeEventListener("scroll", ScrollPosition);
  }, [barWidth]);

  return (
    <BarReading style={{ width: barWidth + "%" }}>
      {parseFloat(Math.round(barWidth - 1)).toFixed(2)} %
    </BarReading>
  );
}

export default ReadingProgressBar;

Implement Reading Progress Bar in React

Head over to src/App.js file, here you have to add both the components. Make sure to add the components in the same hierarchy as given below.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import React from "react";
import Blog from "./features/Blog";
import ReadingProgressBar from "./features/ReadingProgressBar";

function App() {
  return (
    <div className="container mt-5">
      <ReadingProgressBar />
      <Blog />
    </div>
  );
}

export default App;

Start Development Server

Next execute the suggested command to run the React development server.

npm start

After the development server is started, open the browser run the app with the given url.

http://localhost:3000

React Custom Reading Progress Bar Component Tutorial