EN
React - onScroll example
3 points
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:
xxxxxxxxxx
1
// Note: Uncomment import lines while working with compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const appStyle = {
6
width: '150px',
7
height: '150px',
8
whiteSpace: 'nowrap', // used only to display text as not wrapped lines
9
overflow: 'scroll'
10
};
11
12
const handleScroll = () => {
13
console.log('Scroll event ocurred ...');
14
};
15
16
const App = () => {
17
return (
18
<div style={appStyle} onScroll={handleScroll}>
19
<ul>
20
<li>Some very long text test here ...</li>
21
<li>Some very long text test here ...</li>
22
<li>Some very long text test here ...</li>
23
<li>Some very long text test here ...</li>
24
<li>Some very long text test here ...</li>
25
<li>Some very long text test here ...</li>
26
<li>Some very long text test here ...</li>
27
<li>Some very long text test here ...</li>
28
<li>Some very long text test here ...</li>
29
</ul>
30
</div>
31
);
32
};
33
34
const root = document.querySelector('#root');
35
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.