James Stewart
James Stewart

Reputation: 1064

How do I access react-navigation from inside a component that isn't the HomeScreen?

I'm building a React Native app. I have imported createStackNavigator from react-navigation. I'm able to get it working on my Home screen - I click a button, it brings me to a new component. This is the code that I'm using to bring it into my Home.js

// src/components/Home/Home
export class Home extends Component {
  render() {
    return (
      <React.Fragment>
        <Button
          title="Test button"
          onPress={() => this.props.navigation.navigate('Roads')}
        />

        <StatusBar />
        <Header />
        <Menu />
      </React.Fragment>
    );
  }
}

const RootStack = createStackNavigator(
  {
    Home: Home,
    Roads: Roads,
  },
  {
    initialRouteName: 'Home',
  }
);

export default class App extends React.Component {
  render() {
    return <RootStack />;
  }
}

My Home page takes in a Menu which has a list of MenuItems. I am trying to get the MenuItems to jump to the appropriate pages. When I try to bring in the navigation inside MenuItem.js's render method, like so:

// src/components/Roads/Roads
  render() {
    const { navigate } = this.props.navigation;
    console.log(this.props, "props is here");

I get the following error message:

TypeError: undefined is not an object (evaluating 'this.props.navigation.navigate').

Do I need to pass the navigator down in props to Menu.js and then to MenuItem.js? The docs give examples but it seems to be examples that assume you jam all your code into one file rather than across several components.

Have I set this up correctly?

Upvotes: 1

Views: 1862

Answers (1)

needsleep
needsleep

Reputation: 2715

When using a Navigator from react-navigation only the components you declare as Screens inherit the navigation prop (in your case Home and Roads)

This means that you will need to pass it as a prop to its children as you said:

<Menu navigation={this.props.navigation} />
<MenuItem navigation={this.props.navigation} />

In case anyone is wondering how to navigate from a component that isn't inside a Navigator then I suggest reading this part of the react-navigation documentation

https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html

Upvotes: 1

Related Questions