Alireza
Alireza

Reputation: 171

How to use react navigation in other classes?

I have a header and a cart button. This button is for navigate to cart Screen. When I press button I have see error.

Error: undefined is not an object (evaluating '_this3.props.navigation.navigate')

Header is in Header Class in Header file: I use header in other screen like Wallet Screen.

<Header style={styles.headerStyle}>
      <Body>
        <Text>Logo</Text>
      </Body>
      <Right>
      <TouchableOpacity activeOpacity={0.5} onPress={() => {
                      this.props.navigation.dispatch(StackActions.reset({
                        index: 0,
                        actions: [
                          NavigationActions.navigate({ routeName: 'Cart' 
      })
                        ],
                      }))
                    }}>
        <Icon type="MaterialCommunityIcons" name="washing-machine"/>
        {this.state.cartCountNumber != 0 ?(
            <View style={styles.cartCountBox}>
              <Text>{this.state.cartCountNumber}</Text>
            </View>
         ):null}
      </TouchableOpacity>
      </Right>
</Header>

Wallet Screen: When I used on-press in content of wallet worked!

export default class WalletScreen extends React.Component{


render() {
  return (
    <Container>
    <HeaderShow />  // My header is here !!!!!!!!!!!!!!!!!!
    <Content>
    <Text>Wallet Screen</Text>



    // When I use button and on-press here, working fine!



    </Content>
   </Container>
   );
  }

 }

Upvotes: 1

Views: 72

Answers (1)

sdkcy
sdkcy

Reputation: 3548

If you access this.props.navigation in your Wallet screen, when you add navigation prop to Header in Wallet screen, it will work;

export default class WalletScreen extends React.Component {
    render() {
        return (
            <Container>
                <HeaderShow navigation={this.props.navigation}/> // My header is here !!!!!!!!!!!!!!!!!!
                <Content>
                    <Text>Wallet Screen</Text>


                    // When I use button and on-press here, working fine!


                </Content>
            </Container>
        );
    }
}

Upvotes: 3

Related Questions