StackNavigator through Component gives undefined error

Since your Test component does not belong to navigation stack it doesn’t have the navigation prop. You can do couple of things.

Simple one is to pass the navigation to the child component like the example below.

return (
  <View>
        <Text>Hello, Chat App!</Text>
        <Button
          onPress={() => navigate('Chat', { user: userName })}
          title={"Chat with " + userName}
        />
        <Test navigation={this.props.navigation} />
      </View>
);

The second option is, you can use withNavigation from react-navigation. You can find more details about it here

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

const MyComponent = ({ to, navigation }) => (
    <Button title={`navigate to ${to}`} onPress={() => navigation.navigate(to)} />
);

const MyComponentWithNavigation = withNavigation(MyComponent)

withNavigation

withNavigation is a higher order component which passes the
navigation prop into a wrapped component. It’s useful when you
cannot pass the navigation prop into the component directly, or
don’t want to pass it in case of a deeply nested child.

Leave a Comment