React Handle On Scroll Event in Functional Component Tutorial

React onScroll event handler example. In this comprehensive guide, we will learn how to add, handle or use the onScroll event handler in React functional component using React hook and onScroll event handler.

First, we’ll start with creating a new React app. Create the custom function; in our case, we named it onScrollEvent. Next, we will create some fake data using Array.from method; it will be used for vertical scrolling.

This custom function will be invoked as the user starts scrolling. Then, show you how to generate a list of users, and display it on the browser within the limited dimension (height/width) div.

We will keep a progress bar above the user’s list div, and this progress bar will display the progress of how much the user has scrolled back and forth using the onScroll event handler.

Create React App

Head over to console, type the command, then run the command to install the React app.

npx create-react-app my-react-app

Jump to the subsequent step, if already done.

Move into the app directory:

cd my-react-app

Build Component File

Go to src/ folder, here we need to create the features/ folder:

After that, create the functional component by the name of UserList.js:

import React from 'react'

function UserList() {
  return (
    <div></div>
  )
}

export default UserList

Add onScroll Event Handler in React

In this step, we will write the code and show you how to implement the onScroll event handler in React.

Make sure to add the following code into the features/UserList.js file.

import React, { useState } from "react";

const LIST = Array.from({ length: 200 }, (x, i) => {
  return {
    id: i,
    data: `User ${i}`,
  };
});

const UserList = () => {
  const [scrolledProgress, setScrolledProgress] = useState(0);

  const onScrollEvent = (e) => {
    const divHeight = e.currentTarget.clientHeight;
    const scrollingHeight = e.currentTarget.scrollHeight;

    const scrollTop = e.currentTarget.scrollTop;
    setScrolledProgress(((scrollTop + divHeight) / scrollingHeight) * 100);
  };

  return (
    <>
      <div style={styles.scrollBar}>
        <div
          style={{ ...styles.scrolledVal, width: `${scrolledProgress}%` }}
        ></div>
      </div>

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

      <div style={styles.listWrapper} onScroll={onScrollEvent}>
        <div style={styles.data}>
          {LIST.map((item) => (
            <div style={styles.item} key={item.id}>
              {item.data}
            </div>
          ))}
        </div>
      </div>
    </>
  );
};

const styles = {
  listWrapper: {
    width: 600,
    height: 390,
    margin: "0 auto",
    overflowY: "auto",
    background: "#ded8d8",
    overflowX: "hidden",
  },
 
  item: {
    color: "#fff",
    fontSize: "20px",
    textAlign: "center",
    margin: "15px 26px",
    padding: "32px 22px",
    background: "#ff9800",
  },
  scrollBar: {
    width: 600,
    height: 30,
    margin: "auto",
    backgroundColor: "#efefef",
  },
  scrolledVal: {
    height: "100%",
    backgroundColor: "#009688",
  },
  centerAlign: {
    textAlign: "center",
  },
};

export default UserList;

Update Global Component

Now, look for App.js file in the src/ folder, and then add the following code into the file.

import React from "react";
import UserList from "./features/UserList";

function App() {
  return (
    <div>
      <h2>React Handle On Scroll Event Handler Example</h2>
      <UserList />
    </div>
  );
}

export default App;

Run React Server

Lastly, we have to evoke the React app, this can be done by starting the React server.

npm start

React Handle On Scroll Event in Functional Component Tutorial

Conclusion

In this tutorial, we have learned how to work with the onScroll event handler in React.

We saw how to use the useState hook to keep the progress off scrolling events. The currentTarget and scrollTop are crucial in the above code example.

The scrollTop property gets or sets the number of pixels that an element’s content is scrolled vertically.

An element’s scrollTop value measures the distance from the element’s top to its topmost visible content.

Hope you liked the tutorial, have a good day!