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:
// 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.