Languages
[Edit]
EN

React - onScroll example

3 points
Created by:
Eshaal-Wilkinson
774

In this article, we would like to show you onScroll event usage in React.

In the below example, we create <div> element with a scrollbar. When we scroll items inside the div, onScroll triggers handleScroll method which displays messages.

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const appStyle = {
    width: '150px',
    height: '150px',
  	whiteSpace: 'nowrap', // used only to display text as not wrapped lines
    overflow: 'scroll'
};

const handleScroll = () => {
    console.log('Scroll event ocurred ...');
};

const App = () => {
    return (
        <div style={appStyle} onScroll={handleScroll}>
          <ul>
            <li>Some very long text test here ...</li>
            <li>Some very long text test here ...</li>
            <li>Some very long text test here ...</li>
            <li>Some very long text test here ...</li>
            <li>Some very long text test here ...</li>
            <li>Some very long text test here ...</li>
            <li>Some very long text test here ...</li>
            <li>Some very long text test here ...</li>
            <li>Some very long text test here ...</li>
          </ul>
        </div>
    );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

Note:

React documentation says: starting from React 17 the onScroll event does not bubble in React. This matches the browser behavior and prevents the confusion when a nested scrollable element fires events on a distant parent.

 

See also

Alternative titles

  1. React - on scroll event example
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join