How to Create Reading Indicator Progress Bar in React 18

Last Updated on by in React JS

In this tutorial, we will learn how to build a reading progress bar or reading indicator component in React JS using React hooks with function components.

React Reading Indicator example. Reading progress bars are handy for letting your user know how much content has been read and left to be read.

As the name reveals, a reading progress bar is a peculiar yet informative UI component.

It is generally placed on modern web and mobile applications to help us comprehend the reading progress of a post or an article.

It commands us to scroll a bit more unless we ultimately finish reading an article.

It is primarily used to add a little sense of continuity and transparency.

Apart from that, we will learn how to install and use the styled components module to create the reading progress bar in React.

Build New App

To make sure you quickly install a new React app, have the node and npm set up on your development system.

We are using Create React App tool to install a React app.

npx create-react-app react-blog-app

Next, land into the project folder.

cd react-blog-app

Setting Up Bootstrap

We will typically design the basic layout of our app using the Bootstrap library.

Here is the command which will quickly add the bootstrap module in your project.

npm i bootstrap --legacy-peer-deps

In order to harness the power of Bootstrap UI, register the bootstrap in the src/App.js file.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

function App() {
  return <div></div>;
}

export default App;

Install Styled Components

The styled-components allow you to write actual CSS in your React components. It is easy to install; just execute the given command.

npm install styled-components --legacy-peer-deps

Create Reading Bar Indicator in React

Reading bar indicator component requires certain modules and functions to be imported and added in the ReadingIndicator file.

Update code in components/ReadingIndicator.js file.

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

const HorizontalBar = styled.div`
  color: #fff;
  top: 0;
  left: 0;
  position: fixed;
  text-align: center;
  padding: 8px 0 8px 0;
  background: #f12711; /* fallback for old browsers */
  background: -webkit-linear-gradient(
    to right,
    #f5af19,
    #f12711
  ); /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(
    to right,
    #f5af19,
    #f12711
  ); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
`;

function ReadingIndicator() {
  const [indicator, setIndicator] = useState(0);

  const scroller = () => {
    var element = document.documentElement,
      top = element.scrollTop || document.body.scrollTop,
      height = element.scrollHeight || document.body.scrollHeight;
    var calculate = (top / (height - element.clientHeight)) * 100;
    setIndicator(calculate);
  };

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

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

export default ReadingIndicator;

Build Post Function Component

You have to create the components/ folder, also make the Post.js file.

This will be the layout for the post page, where the user scrolls and get to know how much text has been read.

import React from "react";

export default function Post() {
  return (
    <div>
      <h2>React Dynamic Reading Progress Bar Example</h2>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis aliquet
        nisi risus, a lacinia orci fermentum malesuada. Suspendisse eu ex
        faucibus, feugiat nisi id, viverra libero.
      </p>

      <p>
        Aenean pellentesque laoreet sem nec consequat. Cras vulputate quam
        velit, sed ultricies magna placerat ac. Vivamus faucibus tellus
        fringilla posuere gravida. Cras vel commodo sapien. In et nunc eget
        augue feugiat mattis ac non tortor. Nulla scelerisque semper orci, nec
        ultricies lacus.
      </p>

      <p>
        Quisque metus risus, volutpat sed dui eget, vulputate accumsan sem.
        Suspendisse at augue dapibus, volutpat tellus non, laoreet dui. Sed
        condimentum, velit ac tristique efficitur, eros diam hendrerit odio, id
        ultricies metus elit sed magna. Proin bibendum purus elit, sed accumsan
        lectus finibus vel.
      </p>

      <p>
        Cras in ex fringilla nisl ornare condimentum. Nunc eget semper mauris.
        Aliquam pulvinar diam non nibh tempus aliquet. In laoreet, sem eget
        imperdiet viverra, est diam rutrum nisl, et sagittis libero urna nec
        felis. Donec ornare justo vel nulla fringilla cursus quis efficitur
        augue.
      </p>

      <p>
        Vestibulum hendrerit odio ex, in ultricies lectus ultrices sed.
        Suspendisse convallis condimentum nisl, et consequat libero gravida a.
        Vivamus sed est iaculis, interdum metus et, ultricies turpis. Aenean a
        leo vel massa tristique imperdiet suscipit sit amet mauris. In rutrum
        quam non mauris fermentum volutpat.
      </p>

      <p>
        Cras pretium lacus sed enim auctor, id blandit libero porttitor.
        Suspendisse potenti. Curabitur nunc mi, lacinia non tempor eget, lacinia
        ut mi. Donec luctus mauris a augue lobortis ultricies. Aliquam erat
        volutpat. Phasellus eget libero id sem aliquet scelerisque eu eu sem.
      </p>

      <p>
        Nam arcu nibh, suscipit non faucibus et, blandit ac libero. Cras ac
        tortor pellentesque, eleifend est ac, dignissim ex. Sed vel erat nec
        ipsum tempus placerat in in mi. Pellentesque pharetra ultrices
        efficitur. Maecenas ultrices libero vel pellentesque fermentum.
      </p>

      <p>
        Suspendisse pretium, augue at mattis consequat, metus lacus semper
        lorem, interdum venenatis massa lacus convallis augue. Donec venenatis
        ante turpis, eget bibendum nibh commodo vitae. Aliquam ut augue
        facilisis, iaculis neque mollis, molestie justo. In arcu augue, semper
        id dapibus quis, rhoncus sed massa.
      </p>

      <p>
        Praesent maximus varius nibh eget vehicula. Curabitur placerat sapien in
        est semper, sit amet accumsan tellus rutrum. Proin quis turpis a tortor
        hendrerit dapibus ut at turpis. Donec a tincidunt nunc. Donec nec ligula
        erat. Vivamus sed nibh nec turpis semper egestas.
      </p>

      <p>
        Proin cursus erat quam, at sollicitudin est vehicula id. Aliquam
        accumsan est in consequat lacinia. Fusce egestas elit sit amet augue
        pharetra, ac cursus magna tempor. Morbi et sem ipsum. Nullam tempor
        porta sollicitudin.
      </p>

      <p>
        Ut nec ligula mollis, fermentum justo et, mattis felis. Aliquam interdum
        risus ut felis vehicula sodales. Donec metus nibh, malesuada id
        ultricies at, ultrices in nisi.
      </p>

      <p>
        Etiam dictum venenatis cursus. Orci varius natoque penatibus et magnis
        dis parturient montes, nascetur ridiculus mus.
      </p>
    </div>
  );
}

Implement Reading Progress Bar in React

We have to import post and ReadingIndicator components in the App.js global component file.

import React from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import Post from "./components/Post";
import ReadingIndicator from "./components/ReadingIndicator";

function App() {
  return (
    <div className="container">
      <ReadingIndicator />

      <Post />
    </div>
  );
}

export default App;

Test App on Browser

In order to test the app, we first need to start the app and open on the browser with suggested URL.

npm start
http://localhost:3000

How to Create Reading Indicator Progress Bar in React JS

Conclusion

In this tutorial, we went over the series of steps and thoroughly learned how to create and implement the Reading progress bar indicator in React JS component.

We followed the modern and trendy, functional component approach; learned to use React hooks in the functional component to create the custom reading progress bar in React without cumbersome methods.