How to Trigger onScroll Event in React 18 Functional Component

Last Updated on by in React JS

The onScroll events are as important as other event handlers in web development.

In this article, we will explain how to work with the onScroll event handler in React application comfortably.

We will create a React application with the functional component to give you the proper demo.

In the functional component, we will display a list of data with a progress bar with the help of React useState hook.

The user has to scroll to show the hidden part of the list. As the user scrolls up or down, we will trigger an onScroll event handler.

It will calculate the height using client height and scrollHeight DOM properties.

This resulted in updating the progress bar status through the onScroll event handler in React.

React Functional Component On Scroll Event Handling Example

  • Step 1: Build React App
  • Step 2: Create Function Component
  • Step 3: Create Progress Bar with onScroll Event
  • Step 4: Update App Component
  • Step 5: View App on Browser

Build React App

In order to create a brand new project, we first make sure to install Node and Npm on our development system.

Open the terminal by using any code-editor, use the following command to install a new app.

npx create-react-app react-blog

The new application is just created, next move is to enter into the app folder.

cd react-blog

Create Function Component

We need a functional component, therefore make the new folder, name it components/.

Within the new directory, build the new file by the name of Posts.js.

Add the given code to the file to form the functional component.

import React from 'react'

function Posts() {
  return (
    <div>Posts page</div>
  )
}

export default Posts

Create Progress Bar with onScroll Event

Head over to components/Posts.js file, add the provided code to the file.

import React from "react";

const DataItems = Array.from({ length: 55 }, (n, index) => {
  return {
    id: index,
    post: `Post ${index}`,
  };
});

const Posts = () => {
  const [scroller, initScroller] = React.useState(0);
  const handleScroll = (event) => {
    const height = event.currentTarget.clientHeight;
    const barHeight = event.currentTarget.scrollHeight;

    const scrollTop = event.currentTarget.scrollTop;
    initScroller(((scrollTop + height) / barHeight) * 100);
  };

  return (
    <>
      <div style={styles.progressBar}>
        <div style={{ ...styles.scrolled, width: `${scroller}%` }}></div>
      </div>

      <p className="centeredItem">
        <strong style={styles.text}>{scroller.toFixed(2)}%</strong>
      </p>

      <div style={styles.postBlock} onScroll={handleScroll}>
        <div style={styles.post}>
          {DataItems.map((post) => (
            <div style={styles.post} key={post.id}>
              {post.post}
            </div>
          ))}
        </div>
      </div>
    </>
  );
};

const styles = {
  postBlock: {
    width: 555,
    height: 410,
    margin: "0 auto",
    overflowY: "auto",
    background: "rgb(202 216 255)",
    overflowX: "hidden",
  },

  post: {
    color: "#fff",
    fontSize: "22px",
    textAlign: "center",
    margin: "12px 20px",
    padding: "28px 28px",
    background: "#3f51b5",
    borderBottom: "1px solid white",
  },
  progressBar: {
    width: 555,
    height: 32,
    margin: "auto",
    backgroundColor: "#eeeeee",
  },
  scrolled: {
    height: "100%",
    backgroundColor: "#ffc107",
  },
  centeredItem: {
    textAlign: "center",
  },
};

export default Posts;

Update App Component

Look for App.js file, this is the main component from where you can serve the component that we created to handle the onScroll event.

Hence add the code to the App.js file.

import React from "react";
import "./App.css";
import Posts from "./components/Posts";

function App() {
  return (
    <div>
      <h2>React onScroll Event Handler Example</h2>
      <Posts />
    </div>
  );
}

export default App;

View App on Browser

We are now going to start the app development server, you can do it by executing the provided command.

npm start

Check app on browser, if building locally:

http://localhost:3000

How to Trigger onScroll Event in React Functional Component

Conclusion

In this tutorial, we have learned how to trigger the onScroll event in React using React hook in functional components.

Handling scroll events in React is relatively easy and fun.

After going through all the mentioned above steps, you will have an easy idea about how to add an onScroll event in React js functional component.