Search code examples
react-nativereact-navigationstack-navigator

react native, moving between screens


I am using stackNavigator in react native .my problem is I want to move to another screen using stack navigator.

app.js

    const CartStack=createStackNavigator({
      Header:Header,
      Cart:Cart
   )}
   Const Root=createStackNavigator({
      Home:Home,
      Detail:Detail,
      CartStack:CartStack,  
   )}

Home.js

 render() {
       return (
       <Header/>

   )}

The Header Will be show on both screens (Home and Detail) in the header i created a cart button which i want to click on it then will be open a Cart screen. But my code is not working. Please correct my code.


Solution

  • The concept in Zayco's answer is absolutely correct. But I figured out that this.props.navigation.navigate will be undefined in navigationOptions

    Here is the working example of your requirement.

    class Home extends React.Component {
      static navigationOptions = ({navigation}) => ({
        title: 'Home',
        headerRight:(<Button title="Cart" onPress={() => navigation.navigate('Cart')}/>)
      })
      render() {
        return (
          <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Text>Home Scree</Text>
            <Button
              title="Go to Details"
              onPress={() => this.props.navigation.navigate('Details')}
            />
          </View>
        );
      }
    }
    
    class Details extends React.Component {
      static navigationOptions = ({navigation}) => ({
        title: 'Details',
        headerRight:(<Button title="Cart" onPress={() => navigation.navigate('Cart')}/>)
      })
      render() {
        return (
          <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Text>Details</Text>
          </View>
        );
      }
    }
    
    class Cart extends React.Component {
      render() {
        return (
          <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Text>Cart</Text>
          </View>
        );
      }
    }
    
    const RootStack = createStackNavigator(
      {
        Home: Home,
        Details: Details,
        Cart:Cart
      },
      {
        initialRouteName: 'Home',
      }
    );