Search code examples
javascripttypescriptreact-nativereact-native-flatlistflatlist

how to have flat list render only once?


I am trying to print the ComponentTwo Flatlist only once but instead, I am getting the result image1 but instead, I need it to appear like this image 2. I have attached a snack link with the code in it.

Code That will produce the same results as in the images Expo Snack Link


Solution

  • Working Example: Expo Snack

    enter image description here

    Here is how you can fix this, first pass the index value to ComponentOne from App.js

    const App = () => {
     return (
          <SafeAreaView style={styles.container}>
            <FlatList
                data={DATA}
                renderItem={({item, index}) => <ComponentOne name={item.title} index={index}/>}
                keyExtractor={(item) => item.id}
            />
          </SafeAreaView>
      );
    };
    

    Now use that prop value to render ComponentTwo conditionally in ComponentOne like shown below:

    //...const 
    
    ComponentOne = (props: ComponentOneProps) => {
      return (
        <View style={{ margin: 15, backgroundColor: 'yellow' }}>
          <FlatList
            data={recent}
            renderItem={({ item }) => {
              console.log("hello")
              // @ts-ignore
              return props.index == 0?<ComponentTwo name={item.name} />:null;
            }}
            keyExtractor={(item) => item.idd}
          />
    //...