Smooth scrollToOffset in FlatList React Native

1.9k Views Asked by At

I have tried to sychronise-scroll two Flatlist with state but my thought was that scrolling was shaking, lagging and not smooth due to re-rendering. But I tried with referencing React element but it didn't help. The result is the same, scrolling is like a person gotten electrified and shock, that is, shaking.

Code is below:

import * as React from 'react';
import { Text, View, StyleSheet, FlatList, Button } from 'react-native';
import Constants from 'expo-constants';

export default function App() {

  const listRefOne = React.useRef();
  const listRefTwo = React.useRef();

  const handleRef = (listRef, offset) => {

    if (listRef === listRefOne) {
      listRefTwo.current.scrollToOffset({ animated: true, offset: offset });
      console.log('One', offset);
    }

    if (listRef === listRefTwo) {
      listRefOne.current.scrollToOffset({ animated: true, offset: offset });
      console.log('Two', offset);
    }

  };

  return (
    <View style={styles.container}>

      <MyListView listRef={listRefOne} handleRef={handleRef} />
      <MyListView listRef={listRefTwo} handleRef={handleRef} />

    </View>
  );
}

const generateData = () => {
  const temp = [];
  for (var i = 1; i <= 100; i++) {
    temp.push({ id: i, title: `# ${i} Hello` });
  }
  return temp;
};

const mydata = generateData();

const MyListView = ({ listRef, handleRef }) => {

  const handleScroll = (offset) => handleRef(listRef, offset);

  return (
    <FlatList
      ref={(list) => {
        listRef.current = list;
      }}
      style={styles.itemView}
      data={mydata}
      renderItem={({ item }) => (
        <Text style={{ fontSize: 20 }}>{item.title}</Text>
      )}
      keyExtractor={(item) => item.id}
      onScroll={(e) => handleScroll(e.nativeEvent.contentOffset.y)}
    />

  );
};

const styles = StyleSheet.create({
  container: {
    flex: 2,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  itemView: {
    flexGrow: 1,
    backgroundColor: '#efefef',
    margin: 3,
  },
});

Expo Link

0

There are 0 best solutions below