react-navigation - navigating from child component

This is a 3 page example that shows how to pass the navigate function to a child component and how to customize props send to screens from within the StackNavigator

// subcomponent ... receives navigate from parent
const Child = (props) => {
    return (
        <TouchableOpacity 
            onPress={() => props.navigate(props.destination) }>
            <Text>{props.text}>>></Text>
        </TouchableOpacity>
    );
}
// receives navigation from StackNavigator
const PageOne = (props) => {
    return (
        <View>
            <Text>Page One</Text>
            <Child 
                navigate={props.navigation.navigate} 
                destination="pagetwo" text="To page 2"/>
        </View>
    )
}
// receives custom props AND navigate inside StackNavigator 
const PageTwo = (props) => (
    <View>
        <Text>{props.text}</Text>
        <Child 
            navigate={props.navigation.navigate} 
            destination="pagethree" text="To page 3"/>
    </View>
);
// receives ONLY custom props (no nav sent) inside StackNAvigator
const PageThree = (props) => <View><Text>{props.text}</Text></View>

export default App = StackNavigator({
    pageone: { 
        screen: PageOne, navigationOptions: { title: "One" } },
    pagetwo: { 
        screen: (navigation) => <PageTwo {...navigation} text="Page Deux" />, 
        navigationOptions: { title: "Two" } 
    },
    pagethree: { 
        screen: () => <PageThree text="Page III" />, 
        navigationOptions: { title: "Three" }
    },
});

For some reason if you don't want to use withNavigation, the following solution works too. You just have to pass navigation as a prop to your child component.

For example:


export default class ParentComponent extends React.Component {
 render() {
   return (
      <View>
        <ChildComponent navigation={this.props.navigation} />
      </View>
      );
    }
  }

And in child component:

const ChildComponent = (props) => {
   return (
       <View>
         <TouchableOpacity 
           onPress={() => props.navigation.navigate('Wherever you want to navigate')}      
          />
       </View>
      );
    };
export default ChildComponent;

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