2
votes

I have a vertical FlatList component and two buttons as TouchableOpacity, how do I perform scrolling of the FlatList with the buttons,

i.e. 'scrolling the FlatList towards bottom` and 'scroll the FlatList towards top'?

Minimal Example:

<View>
    <FlatList/>
    <TouchableOpacity>
        <Text>Scroll towards Top</>Text
    </TouchableOpacity>
    <TouchableOpacity>
        <Text>Scroll towards Bottom</>Text
    </TouchableOpacity>
</View>
2
Andus, check if my answer can help you - abranhe

2 Answers

6
votes

This is not difficult to accomplish, The <Flatlist/> component already have methods to do that.

I have created a simple demo for you: https://snack.expo.io/@abranhe/flatlist-scroll

I have created a custom <Button/> and <Card/> components. I am creating an array with some random data with this format

const data = [
 { message: 'Random Message' },  { message: 'Random Message' }
]

I am adding a reference to the <Flatlist/> by adding

ref={ref => (this.flatlist = ref)}

Then I call the methods and that's it.

<Button title="▼" onPress={() => this.flatlist.scrollToEnd()} />

The whole source code:

import React from 'react';
import { Text, View, FlatList, StyleSheet } from 'react-native';
import { random } from 'merry-christmas';
import Card from './components/Card';
import Button from './components/Button';

const data = [...Array(10)].map(i => ({ message: random() }));

export default () => (
  <View style={styles.container}>
    <FlatList
      ref={ref => (this.flatlist = ref)}
      data={data}
      renderItem={({ item }) => <Card gretting={item.message} />}
    />
    <View style={styles.bottomContainer}>
      <Button
        title="▲"
        onPress={() => this.flatlist.scrollToIndex({ index: 0 })}
      />
      <Button title="▼" onPress={() => this.flatlist.scrollToEnd()} />
    </View>
  </View>
);
1
votes

You can use a scrollView component