React Native
onScroll
Learn the scroll event with onScroll.
The onScroll event
The onScroll prop fires as the user scrolls. You pass it a function; on every scroll gesture React Native calls that function with an event object.
The most useful piece of the event object is nativeEvent.contentOffset.y. It tells you how far the content has been scrolled from the top, in pixels. The value grows as you scroll down.
Common uses: shrink a header based on scroll position, update a progress bar, or load more data near the bottom. Avoid expensive work; every gesture fires the handler.
Read the contentOffset value
From the event parameter of the handler, you read the vertical scroll amount with event.nativeEvent.contentOffset.y. You can assign it to a const or let variable.
Example: const onScroll = (event) => {`{ const y = event.nativeEvent.contentOffset.y; console.log(y); }`}. Every scroll logs y to the console.
For horizontal scroll use .x. Because the handler fires very often, do not run heavy work directly; apply a throttle if needed. You will see that topic at the advanced level.
Exercise Log the scroll amount
Write a <ScrollView> and pass a function to its onScroll prop. The function takes event and logs event.nativeEvent.contentOffset.y with console.log. Add a few <Text> rows inside.
Show example solution
function App() {
return (
<ScrollView onScroll={(event) => {
console.log(event.nativeEvent.contentOffset.y);
}}>
<Text>Row one</Text>
<Text>Row two</Text>
<Text>Row three</Text>
<Text>Row four</Text>
</ScrollView>
);
}
export default App;
Test yourself
-
When does onScroll fire?
- Only when a button is pressed
- Once when the component mounts
- Only when the screen rotates
- When the user scrolls
Show answer
Only when a button is pressed — every scroll gesture fires onScroll.
-
Add the event parameter
import { ScrollView } from 'react-native';
const handleScroll = (____) => {
const y = event.nativeEvent.contentOffset.y;
console.log(y);
};
Show answer
import { ScrollView } from 'react-native';
const handleScroll = (event) => {
const y = event.nativeEvent.contentOffset.y;
console.log(y);
};
-
Match the onScroll parts
- onScroll
- Listens to the scroll event
- nativeEvent
- Native event data
- contentOffset.y
- Vertical scroll amount
- contentOffset.x
- Horizontal scroll amount
Next lesson: RefreshControl