CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

App.js
import { ScrollView, Text } from 'react-native';

// write the ScrollView with onScroll here

Sample solution

App.js
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;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When does onScroll fire?

  • Only when a button is pressed Correct answer
  • Once when the component mounts
  • Only when the screen rotates
  • When the user scrolls

Explanation: every scroll gesture fires onScroll.

2 Add the event parameter

Question
import { ScrollView } from 'react-native';

const handleScroll = (____) => {
  const y = event.nativeEvent.contentOffset.y;
  console.log(y);
};
Answer
import { ScrollView } from 'react-native';

const handleScroll = (event) => {
  const y = event.nativeEvent.contentOffset.y;
  console.log(y);
};

Explanation: the event parameter carries the event object.

3 Match the onScroll parts

Term Meaning
onScroll Listens to the scroll event
nativeEvent Native event data
contentOffset.y Vertical scroll amount
contentOffset.x Horizontal scroll amount

All lessons in Beginner