th3g3ntl3man
th3g3ntl3man

Reputation: 2106

Creation of a new component with navigation fields

I try to create a new react-native component that contains two button. I define two property next to going on the next page and prev to going in the precedent page but I have this error:

undefined is not an object (evaluating '_this.props.navigation.navigate')

I found so much question similar this but I don't found any valid solution.

This is the code:

import PropTypes from 'prop-types'
import React, { Component } from 'react';
import { View, StyleSheet, Button } from 'react-native';

export default class ButtonNavigation extends Component {

  static propTypes = {
    next: PropTypes.string,
    prev: PropTypes.string,
  }

  render() {

    const { next, prev } = this.props;

    return (
      <View style={styles.bottomContainer}>
        <View style={styles.buttonContainer}>
          <Button onPress={() => this.props.navigation.navigate(next)} title='Indietro' color='#00b0ff'/>
        </View>
        <View style={styles.buttonContainer}>
          <Button onPress={() => this.props.navigation.navigate(prev)} title='Avanti' color='gold'/>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  },
  bottomContainer: {
    flex: 1,
    flexDirection: 'row',
    position: 'absolute',
    bottom: 10,
    padding: 20,
    justifyContent: 'space-between'
  },
  text: {
    fontSize: 30,
  },
  buttonContainer: {
    flex: 1,
    padding: 20,
    justifyContent: 'center',
    alignContent: 'center',
  }
});

I include the object in the other page in this way:

<ButtonNavigation next={'NumberVehicle'} prev={'Home'}/>

Upvotes: 0

Views: 43

Answers (2)

Kevin Etore
Kevin Etore

Reputation: 1134

In your <ButtonNavigation next={'NumberVehicle'} prev={'Home'}/> you need to add the navigation object as a prop. So something like:

<ButtonNavigation
  next={'NumberVehicle'}
  prev={'Home'}
  navigation={this.props.navigation} 
/>

(Make sure to replace this.props.navigation if it differs from the actual navigation object)

And after you can do:

const { next, prev, navigation } = this.props;

and

navigation.navigate(..)

Upvotes: 1

hong developer
hong developer

Reputation: 13926

You can change this

<ButtonNavigation next={this.props.navigation.navigate('NumberVehicle')} prev={this.props.navigation.navigate('Home')}/>
      <View style={styles.bottomContainer}>
        <View style={styles.buttonContainer}>
          <Button onPress={() => this.props.next} title='Indietro' color='#00b0ff'/>
        </View>
        <View style={styles.buttonContainer}>
          <Button onPress={() => this.props.prev} title='Avanti' color='gold'/>
        </View>
      </View>

Upvotes: 0

Related Questions