user7381027
user7381027

Reputation: 41

React Native: Cannot read property 'navigation' of undefined

I am trying to make an onPress function such that when the menu icon is clicked, my drawer navigation will open. However, I am getting this error: Unhandled JS Exception: Cannot read property 'navigation' of undefined.

Here's my code for HeaderComponent.js

import React from 'react';
import { StyleSheet } from 'react-native';
import { Header, Left, Icon, Body, Title, Right } from 'native-base';

const HeaderComponent = (props) => {
const { menuIconStyle } = styles;

return (
    <Header>
        <Left>
            <Icon
                style={menuIconStyle}
                name="menu"
                onPress={() => this.props.navigation.openDrawer()}
            />
        </Left>
        <Body>
            <Title>{props.headerText}</Title>
        </Body>
        <Right>

        </Right>
    </Header>
);
}

export default HeaderComponent;

const styles = StyleSheet.create({
menuIconStyle: {
    paddingLeft: 15,
},
});

Would appreciate a solution. Thanks!

Upvotes: 0

Views: 1726

Answers (2)

Your component is not a ES6 class but a function. So, you cannot use this.props because it doesn't exist.

onPress={() => props.navigation.openDrawer()}

use this instead.

Upvotes: 0

Reza Madani
Reza Madani

Reputation: 353

You should pass navigation props from parent to child,like this:

<HeaderComponent navigation={this.props.navigation} />

then you can use navigation in your child component

Upvotes: 1

Related Questions