Marko
Marko

Reputation: 545

Passing flatlist render "Item" to a function. React Native (kinda a js question)

Right now I have a flatlist that contains a bunch of firebase objects (books), when one of the book are clicked, I want to return a page with more data about that specific book. Right now each book it an object, where title is one of the values, this is what is shown on the flatlist. I want to be able to show all of the other object attributes when the new detailed page is opened. If there is a better way of doing this, let me know but this is the logic that I was trying to go with.

(this is in the flatlist)
                    renderItem={({ item }) => (
                        <TouchableOpacity onPress={bookOnPressHandler} activeOpacity={0.9} style={styles.flatListStyle}>
                            <View>

                                <Text>{item.title}</Text>

                            </View>
                        </TouchableOpacity>
                    )}
                />

then the handler:

    const bookOnPressHandler = (item) => {
        //this holds the title of the book
        title = item.title
        console.log(title)
        navigation.navigate('booknotes')
    }

I obviously need to pass item into the function, what it is right now wont work. How would I get access to "Item" in the function? once I set the item = to something, I can use it on the new page.

I feel like there is a better method than this and that this might even not work? I know this is a common thing to do in apps, all help is really appreciated. Also sorry if its obvious, Im pretty new to this language and framework!

Upvotes: 2

Views: 1722

Answers (1)

Ajin Kabeer
Ajin Kabeer

Reputation: 2186

Since you already have access to the required object that is to be passed to the next screen, it's very easy, you can pass it along with the navigation object as a route param.

It's always good to isolate the prop functions to separate functions to avoid unnecessary re-render of the component.

Here is an example.

 <FlatList
        ref={ref}
        contentContainerStyle={styles.contentContainer}
        scrollEventThrottle={16}
        numColumns={2}
        data={exploreData}
        initialNumToRender={2}
        renderItem={renderItem}
        keyExtractor={(item: any) => item.id.toString()}
        })}
      />

Here is the renderItem function:

const renderItem = ({ item }) => {
  const handleOnPress = () => navigation.navigate("Profile", { item });
  return (
    <TouchableWithoutFeedback
      onPress={handleOnPress}
    >
      <ImageBackground
        source={{ uri: img }}
        style={styles.image}
        imageStyle={styles.background}
      />
    </TouchableWithoutFeedback>
  );
};
//Profile Screen
const Profile = ({ navigation, route }) => {
  const { item } = route.params;
  console.log(item);
};

Upvotes: 4

Related Questions