react-nativereact-native-flatlistrouteparams

How can I get current index through FlatList?


I'm passing data to details screen with Navigation params, everything works correct, the only thing that I want to pass clicked current level index to Object.entries[currentIndex], I'm not sure how can I get that.

<FlatList
          data={data}
          keyExtractor={(item) => item.index}
          renderItem={({ item, index }) => (
            <View>
              {item.sTask?.map((levels, i) => (
                <View>
                  <TouchableOpacity
                    onPress={() => navigation.navigate('Tasks', { item })}
                    style={{
                      backgroundColor: '#33333325',
                      paddingHorizontal: 20,
                      paddingVertical: 10,
                      borderRadius: 10,
                      marginVertical: 20,
                      marginHorizontal: 20,
                    }}
                  >
                    <Text>{Level 1}</Text>
                  </TouchableOpacity>
                   
                   <TouchableOpacity>
                     {Another level...}
                   </TouchableOpacity>
                </View>
              ))}
            </View>
          )}
        />

Details screen:

  const [currentTaskGroupIndex, setCurrentTaskGroupIndex] = useState(0); <---- We need to set current index somehow to current clicked index

  //Test item params data
  useEffect(() => {
    const mapData = item?.sTask?.map((tasks) => {
      return Object.entries(tasks)[currentTaskGroupIndex].map((level) => {
        // console.log(level);
      });
    });
  }, [item]);

No matter which level i clicked, i'm getting Level 1 details


Solution

  • You need to do like :

     onPress={() => navigation.navigate('Tasks', { item:item, index:i })}
    

    and then in details screen:

    const indexParam = props?.route?.params?.index ?? 0
    
    const [currentTaskGroupIndex, setCurrentTaskGroupIndex] = useState(indexParam); <---- We need to set current index somehow to current clicked index
    
      //Test item params data
      useEffect(() => {
        const mapData = item?.sTask?.map((tasks) => {
          return Object.entries(tasks)[currentTaskGroupIndex].map((level) => {
            // console.log(level);
          });
        });
      }, [item]);
    

    Hope it helps. feel free for doubts