Skip to content
Advertisement

Press tab to scroll to top of flatlist

I would like to implement scrolling to top. My tab is a flatlist, and when users scroll down the flatlist, they have to scroll back up. Instagram and Twitter allow you to press the tab to scroll back up, I am wondering how to implement it in my own app.

Here is the tab I want to implement scrolling to top:

//Bottom Tabs
function Tabs() {

...

  <Tab.Screen 
    name="Home" 
    component={globalFeedStackView}
    options={{
      tabBarLabel: ' ',
      tabBarIcon: ({ color, size }) => (
        <Ionicons name="ios-home" size={size} color={color} />
      ),
    }}
  />

}

And the class component for the tab above:

class GlobalScreen extends React.Component {

constructor(props) {
    super(props);

    this.state = {
      isLoading: true,
      globalPostsArray: [],
      navigation: this.props.navigation,
    };
}

async componentDidMount() {
    this.getCollection()
    Analytics.setUserId(Firebase.auth().currentUser.uid)
    Analytics.setCurrentScreen("GlobalScreen")
}

...

render() {
    return (
        <View style={styles.view}>
            <FlatList
                data={this.state.globalPostsArray}
                renderItem={renderItem}
                keyExtractor={item => item.key}
                contentContainerStyle={{ paddingBottom: 50 }}
                showsHorizontalScrollIndicator={false}
                showsVerticalScrollIndicator={false}
                onRefresh={this._refresh}
                refreshing={this.state.isLoading}
                onEndReached={() => {this.getMore()}}
            />
            <KeyboardSpacer />
        </View>
    )
}

According to react navigation I can do something like this:

import * as React from 'react';
import { ScrollView } from 'react-native';
import { useScrollToTop } from '@react-navigation/native';

class Albums extends React.Component {


render() {
    return <ScrollView ref={this.props.scrollRef}>{/* content */}</ScrollView>;
  }
}

// Wrap and export
export default function(props) {
  const ref = React.useRef(null);

  useScrollToTop(ref);

  return <Albums {...props} scrollRef={ref} />;
}

But this solution is for a scrollview, and I am using a flatlist.

How can I implement pressing a tab to scroll to the top of my flatlist?

Advertisement

Answer

scrollToOffset

you can do it the same way with a ref on your FlatList :

import * as React from 'react';
import { FlatList } from 'react-native';

class Albums extends React.Component {


render() {
  return <FlatList ref={this.props.scrollRef} />;
}


// Wrap and export
export default function(props) {
const ref = React.useRef(null);

  ref.scrollToOffset({ animated: true, offset: 0 });

  return <Albums {...props} scrollRef={ref} />;
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement