Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.props.onPress is not a function

I have a HomePage.js which contains About Us button, and when I click on that button I want to show AboutUs.js. The HomePage.js is displayed correctly, however, when I click on the button it gives me the following error: this.props.onPress is not a function. (In 'this.props.onPress(e)', 'this.props.onPress' is an instance of Object)

I have App.js

import React, { Component } from 'react';
import { StackNavigator } from 'react-navigation';
import HomePage from './HomePage';
import AboutUs from './AboutUs';


const App = StackNavigator({
    HomePage: {
        screen: HomePage,
        navigationOptions: {
            header: () => null
        }
    },
    AboutUs: { 
      screen: AboutUs,
        navigationOptions: {
          header: () => null
        }
     }
});

export default App;

Then I have a reusable component Button.js:

import React from 'react';
import { Text, TouchableOpacity } from 'react-native';

const Button = ({ onPress, children }) => {
    return (
        <TouchableOpacity onPress={onPress}>
            <Text>{children}</Text>
        </TouchableOpacity>
    );
};

export { Button };

HomePage.js which is rendering the Button component. When I press it I get the above mentioned error

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { Button } from './Button.js';
import AboutUs from './AboutUs';

class HomePage extends Component{

  render() {
    const { navigate } = this.props.navigation;
    return(
      <View>
        <Button
          onPress={() => navigate('AboutUs'), { name: 'About Us' }}
          >About Us</Button>
      </View>
    )
  }
}

export default HomePage;

AboutUs.js

import React, { Component } from 'react';
import { Text, View } from 'react-native';

class AboutUs extends Component {
    render() {
        return (
      <View>
            <Text>About us!</Text>
      </View>
        );
    }
}

export default AboutUs;
like image 758
Tom Bomb Avatar asked Nov 12 '17 19:11

Tom Bomb


3 Answers

This is not a valid function reference

onPress={() => navigate('AboutUs'), { name: 'About Us' }}

seems like you mixed up { name: 'About Us' } inside the function ref instead of as a prop to Button

like image 80
Sagiv b.g Avatar answered Nov 14 '22 04:11

Sagiv b.g


I had a similar issue with the same error: "this.props.onPress is not a function" The mistake I made was using:

onPress={this.props.incrementCount()}

where the correct syntax is:

onPress={ () => this.props.incrementCount()}

the latter returns the results of the function.

like image 8
Bruce Seymour Avatar answered Nov 14 '22 03:11

Bruce Seymour


for me it was i missed a curly brackets

onPress={() => {navigate('AboutUs'), { name: 'About Us' }}}

like image 2
Yedu Krishnan S M Avatar answered Nov 14 '22 05:11

Yedu Krishnan S M