CodeBlanks Logo Icon CodeBlanks

Summary - ScrollView

Combine ScrollView, horizontal and RefreshControl to write a gallery.

Summary - ScrollView

This group covered the basics of scrolling regions. ScrollView scrolls content with a finger; horizontal enables sideways scroll; contentContainerStyle styles the inner content wrapper.

onScroll calls a function while scrolling; you read the vertical position with event.nativeEvent.contentOffset.y. RefreshControl is the pull-to-refresh mechanism; you drive the spinner with the refreshing state.

Now you will combine these in two mini tasks: first a horizontal gallery, then a list with pull-to-refresh.

Practice Horizontal card gallery

Write a horizontal ScrollView with three <View> cards. Each card is styled width: 140 and height: 140 with a <Text> inside. Give contentContainerStyle a padding: 8.

Starter code

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

// write the horizontal gallery here

Sample solution

App.js
const styles = { card: { width: 140, height: 140, margin: 6, backgroundColor: '#f0f0f0' } };
function App() {
  return (
    <ScrollView horizontal contentContainerStyle={{ padding: 8 }}>
      <View style={styles.card}><Text>One</Text></View>
      <View style={styles.card}><Text>Two</Text></View>
      <View style={styles.card}><Text>Three</Text></View>
    </ScrollView>
  );
}
export default App;

Practice A list with refresh

Write a ScrollView with four <Text> rows. Pass <RefreshControl refreshing={'{refreshing}'} onRefresh={'{handleRefresh}'} /> to its refreshControl prop. Define refreshing with useState(false) and a handleRefresh that flips it back to false after two seconds.

Starter code

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

// write the refreshable list here

Sample solution

App.js
function App() {
  const [refreshing, setRefreshing] = useState(false);
  const handleRefresh = () => {
    setRefreshing(true);
    setTimeout(() => setRefreshing(false), 2000);
  };
  return (
    <ScrollView refreshControl={<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />}>
      <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 Match all the concepts

Term Meaning
horizontal Horizontal scroll
contentContainerStyle Inner wrapper style
onScroll Scroll event
RefreshControl Pull-to-refresh

2 What enables pull-to-refresh?

  • RefreshControl
  • horizontal
  • contentOffset Correct answer
  • padding

Explanation: RefreshControl works with refreshing and onRefresh.

All lessons in Beginner