Home > Mobile >  navigate inside renderItem of Flatlist
navigate inside renderItem of Flatlist

Time:08-25

I have a component InventoryScreen, which holds a Flatlist like this:

 <FlatList
            numColumns={2}
            data={filteredData}
            keyExtractor={(item, index) => index.toString()}
            renderItem={renderItem}
            stickyHeaderIndices={[0]}
            keyboardDismissMode={"on-drag"}>
</FlatList>
<TouchableOpacity
      onPress={() => navigation.navigate("ItemScreen") }> // <--- Here, it works.
</TouchableOpacity


Inside InventoryScreen, I can use navigation.

renderItem:

const renderItem = ({ item }: { item: ItemResponse }) => {
  return <ItemView item={item} />;
};

ItemView

const ItemView = ({ item }: { item: ItemResponse }) => {
  return (
<TouchableOpacity
      onPress={() => navigation.navigate("ItemScreen") }> // <--- This is what I want.
</TouchableOpacity

But, because there is no navigation available in ItemView, I cant navigate inside there. When trying to pass navigation to the renderItem gives me an error inside the FlatList:

Property 'navigation' is missing in type 'ListRenderItemInfo<ItemResponse>' but required in type '{ item: ItemResponse; navigation: any; }'.

How can I access navigation inside ItemView ?

CodePudding user response:

Please try this Root Component

const RootComp = ({navigation})=>{

    const renderItem = ({ item }: { item: ItemResponse }) => {
      return <ItemView item={item} navigation={navigation} />;
    };

return (
<FlatList
            numColumns={2}
            data={filteredData}
            keyExtractor={(item, index) => index.toString()}
            renderItem={renderItem}
            stickyHeaderIndices={[0]}
            keyboardDismissMode={"on-drag"}>
</FlatList>
)

}

ItemView

const ItemView = ({ item, navigation }: { item: ItemResponse }) => {
  return (
<TouchableOpacity
      onPress={() => navigation.navigate("ItemScreen") }> // <--- This is what I want.
</TouchableOpacity

CodePudding user response:

you can pass in the navigation props like a normal prop from the parent

const renderItem = ({ item }: { item: ItemResponse }) => {
  return <ItemView item={item}  nav={props.navigation} />;
};

hope this works

CodePudding user response:

Im hoping you have access to navigation here? then just pass navigation as props

  const renderItem = ({ item }: { item: ItemResponse }) => {
      return <ItemView item={item} navigation={navigation} />;
    };

And use it like this :

const ItemView = ({ item ={}, navigation = {}}: { item: ItemResponse }) => {
  return (
<TouchableOpacity
      onPress={() => navigation.navigate("ItemScreen") }> // <--- This is what I want.
</TouchableOpacity
  • Related