Search code examples
react-nativereact-navigationreact-native-flatlistflatlist

How to use React Navigation with an element inside of a FlatList's Header?


I can navigate perfectly within the renderItem, but when i try within the component that I use in the header when I click it says "undefinded is not an object (evaluating '_this.props.navigation.navigate')

This is how Im trying to navigate within the component thats been passed to the FlatLists's header <TouchableOpacity onPress={() => this.props.navigation.navigate('Profile', { data: info })}>


Solution

  • Just a hunch, but my guess is the component is being passed for ListHeaderComponent instead of a rendered element with the navigation prop.

    For example:

    function Parent(props) {
      // Here the FlatList will render the header as <MyHeader /> with no props
      // If this.props.navigation is called in MyHeader it will be undefined
      return (
        <FlatList ListHeaderComponent={MyHeader} ... />
      );
    }
    

    vs

    function Parent(props) {
      // here MyHeader is rendered as an element first, passing through
      // the necessary navigation prop
      const headerElement = (<MyHeader navigation={props.navigation} />);
      return (
        <FlatList ListHeaderComponent={headerElement} ... />
      );
    }