Saeed Heidarizarei
Saeed Heidarizarei

Reputation: 8916

Access the navigation prop from any component via React Navigation

I have 3 js File, 2 pages (HomePage and SecondPage) and 1 ( ComponentBlock that added to HomePage).
How Can I Navigate from ComponentBlock to SecondPage? I mean, When I use onPress Button Directly in HomePage everythings is okey and I can navigate from home to second and second to Home, But I Can't Navigate from ComponentBlock that added in Home Page to second.

HomePage:

import {createStackNavigator} from 'react-navigation';
import Second from './8-SecondPage'
import ComponentBlock from './8-Component-Block';

class Home extends React.Component {
  render() {
    return (
      <ComponentBlock />
    );
  }
}

const App = createStackNavigator(
  {
    Home: {screen: Home},
    Second: {screen: Second},
    Third: {screen: ComponentBlock},
  },
);

export default App;

SecondPage:

export default class Second extends Component {
  render() {
    return (
      <View>
        <TouchableOpacity
          onPress={() => this.props.navigation.navigate('Home')}
        >
          <Text>Go to Home Page</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

ComponentBlock:

export default class ComponentBlock extends Component {
  render() {
    return (
      <View>
        <Text>ComponentBlock</Text>
        <TouchableOpacity
          onPress={() => this.props.navigation.navigate('Second')}
        >
          <Text>Go to Second Page</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

Upvotes: 2

Views: 854

Answers (1)

Mortada
Mortada

Reputation: 199

in BlockComponent file

import { withNavigation} from 'react-navigation';
export default withNavigation(BlockComponent);

you can now use

this.props.navigation.navigate('SecondPage');

Upvotes: 3

Related Questions