react-navigation - navigating from child component

kcuhcx2 picture kcuhcx2 · Sep 18, 2017 · Viewed 11.9k times · Source

I have a leaderboard which calls a component and passes it data to it like so:

   _renderItem =({item}) => (
    <childComponent
        key={item._id}
        id={item._id}
        name={item.name}
    />
   );

And inside the childComponent I try do this:

    <TouchableOpacity onPress={() => this.props.navigation.navigate("Profile", { id: this.props.id})} >
       <View>
         <Right>
              {arrowIcon}
         </Right>
       </View>
    </TouchableOpacity>

Where I am hoping that it will then go to the profile page and grab the correct data based on the id passed to it. The issue is that when I click the arrow to go to the profile page I get the error Cannot read property 'navigate of undefined. I have put both the leaderboard and childComponent in my HomeDrawerrRoutes.js and MainStackRouter.js. Any help would be great, thanks.

Answer

Adarsh picture Adarsh · Jul 14, 2018

There is an easy Solution for this,

use withNavigation . it's a higher order component which passes the navigation prop into a wrapped Component.

example child component

import React from 'react';
import { Button } from 'react-native';
import { withNavigation } from 'react-navigation';

class ChildComponent extends React.Component {
  render() {
    <View
      onPress = {()=> this.props.navigation.navigate('NewComponent')}>
     ... logic
    </View>

  }
}

// withNavigation returns a component that wraps ChildComponent and passes in the
// navigation prop
export default withNavigation(ChildComponent);

for more details : https://reactnavigation.org/docs/en/connecting-navigation-prop.html