React-Native

Detect scrollable in FlatList of React-Native

버그매니저 2020. 10. 28. 09:42

Here is Code.

check isScrollable function and onContentSizeChange in FlatList.

import React from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text, StatusBar,Dimensions } from 'react-native';

const DATA = [
  {
    id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
    title: 'First Item',
  },
  {
    id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
    title: 'Second Item',
  },
  {
    id: '58694a0f-3da1-471f-bd96-145571e29d72',
    title: 'Third Item',
  },
];

const Item = ({ title }) => (
  <View style={styles.item}>
    <Text style={styles.title}>{title}</Text>
  </View>
);

const App = () => {
  const renderItem = ({ item }) => (
    <Item title={item.title} />
  );

  const  isScrollable(width, height) {
  		//1) check deviceHeight and content height
        //2) compare them 
        
        const screenHeight = Math.floor(Dimensions.get("window").height);
        return Math.floor(height) > screenHeight;
    }

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={DATA}
        renderItem={renderItem}
        keyExtractor={item => item.id}
        contentContainerStyle={{flexGrow:1}}
        onContentSizeChange={(width, height) => {
        
        						//------------you can check right here--------------
                                        // get content height from onContentSizeChange
                                        const checkScrollable = isScrollable(width, height);
                                        console.log("checkScrollable",checkScrollable);
                                 
                                }}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: StatusBar.currentHeight || 0,
  },
  item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
});

export default App;
반응형