React Native error: encountering the error message "undefined is not an object '_this3.props.navigation()'"

I am encountering an error in the navigationOptions() function when running my React app, but everything is working correctly in the render() function.

App.js

import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';
import AppNavigator from './routes.js'


class App extends Component {
   render() {
      return (
         <AppNavigator />
      )
   }
}
export default App

routes.js

import React from 'react'
import Home from './home.js'
import Phone from './phone.js'
import PhoneScreen from './phoneScreen.js'
import {createStackNavigator, createAppContainer} from 'react-navigation';


const MainNavigator = createStackNavigator({

  home: {screen: Home},
  add: {screen: Phone},
  userScreen: {screen: PhoneScreen},

});

const AppNavigator = createAppContainer(MainNavigator);

export default AppNavigator;

home.js

import React from 'react'
import { TouchableOpacity, Text, View, TouchableHighlight, StyleSheet, Button } from 'react-native';
import { Actions } from 'react-native-router-flux';
import {AsyncStorage} from 'react-native';


class Home extends React.Component {

constructor(props) { 
super(props); 
}

static navigationOptions = {
headerTitle: 'Contacts',
headerRight: (
<Button
onPress={() => this.props.navigation.navigate('add')}
title="Create New Contact"
color="#000000"
size="20"
/>
),
     };
}
export default Home;

"undefind is not an object(evaluating '_this3.props.navigation')"

Please provide a solution.

Answer №1

According to the React Navigation Documentation:

The context of 'this' in navigationOptions does not refer to the HomeScreen instance, making it impossible to use setState or any other instance methods on it. This is a crucial point as often, buttons in the header are expected to interact with the screen where the header is located.

It is evident that in this scenario, the interpretation of this may be misleading. The documentation provides a functional example:

 class HomeScreen extends React.Component {
  static navigationOptions = ({ navigation }) => {
    return {
      headerTitle: <LogoTitle />,
      headerRight: (
        <Button
          onPress={navigation.getParam('increaseCount')}
          title="+1"
          color="#fff"
        />
      ),
    };
  };

  componentDidMount() {
    this.props.navigation.setParams({ increaseCount: this._increaseCount });
  }

  state = {
    count: 0,
  };

  _increaseCount = () => {
    this.setState({ count: this.state.count + 1 });
  };

  /* later in the render function we display the count */
}

By converting navigationOptions from an object to a function, accessing the navigation reference becomes feasible, allowing successful traversal.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

contrasting module export approaches

Let me clarify that my query does not revolve around the disparity between module.exports and exports. Instead, I am interested in understanding the contrast between exporting a function that generates an object containing the functions to be shared upon i ...

What is causing my reusable component to malfunction when used in conjunction with the "setInterval" function?

I have created a custom <Loader /> component in which I can pass the text it is rendering and the speed as props. The code for the component is shown below: class Loader extends Component { constructor(props) { super(props); this.state = { ...

Wildcard for keys in JavaScript objects and JSON

I have a JSON object that contains specific key-value pairs, and I am attempting to manipulate strings based on this object. Here is an example of the JSON structure: { "foo %s": "bar %s", "Hello %s world %s.": "W ...

What could be causing the jQuery .load() function to trigger twice?

While using jQuery 1.4 along with jQuery History, I noticed that Firebug/Web Inspector are displaying 2 XHR GET requests on each page load (which doubles when visiting the homepage (/ or /#). For example, if you visit this or any other page with Firebug e ...

Utilizing NGINX as a reverse proxy for secure communication with Node.js

I'm currently running an NGINX server setup as a reverse-proxy server for a node application. I am now trying to enable HTTPS, but every time I attempt to access the site via HTTPS, I encounter a "502: Bad Gateway" error. server { listen 80; ...

Utilizing ReactJs to Generate a Random Number for Visualization in a Material UI Progress Bar

I am looking to generate a random number for my test functionality in order to display it within a Material UI Progress bar. I have successfully implemented this piece of JavaScript code on JSFiddle, but now I want to integrate it into my React application ...

The MUI makeStyles() class has been implemented, yet the styles are not being displayed when using classList.add('class-name')

Currently, I am utilizing MUI makeStyles() to create a series of CSS classes. Within these classes, I am dynamically including and excluding one specific class to my Box element during file drag-and-drop events. The class is successfully added, as I can o ...

When the script is placed at the end of the file, document.getElementById() is still returning null

I need assistance with running a JavaScript function that is located at the end of my .aspx file. This is the div tag in question: <div id="div_NRContainer" oninit="div_NRContainer_Init" class="panelContainer" runat="server"> Following this, with ...

The persistent redirection issue in Node.js - Middleware

Currently, I am in the process of developing a middleware using node js and express. The main objective of this middleware is to redirect users to a login page if they are not authenticated. Although the redirection to the login page works as intended, th ...

Ways to ensure the text on my website scrolls into view as the user navig

Is there a way to have my text show up as I scroll? I came across this , but I'm interested in how it actually functions. I saw a similar inquiry before, but it doesn't make sense to me. Can someone please explain or provide some examples on how ...

"The process of logging in to Facebook on Ionic app speeds up by bypassing

I'm facing a minor issue with Facebook login in Ionic. I've tried using Async - Await and various other methods to make it wait for the response, but nothing seems to work. The login function is working fine, but it's not pausing for me to p ...

What is the best way to apply a filter to an array of objects nested within another object in JavaScript?

I encountered an issue with one of the API responses, The response I received is as follows: [ {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "US"}, {type: "County", countyNa ...

How to achieve an endless cycle using Promise recursion in a NodeJS environment

I am planning to replace my blocking infinite while loop with promises. My run function is quite simple - it lights up an LED and then turns it off before moving on to the next one. Since Promises do not work inside while loops, I'm exploring how I c ...

"In Typescript, receiving the error message "Attempting to call an expression that is not callable" can be resolved

I am in the process of creating a function that matches React's useState signature: declare function useState<S>( initialState: S | (() => S), ): [S, React.Dispatch<React.SetStateAction<S>>]; Below is an excerpt from the functi ...

The specific module 'franc' does not have the export named 'default' as requested

Every time I attempt to use the franc package, I encounter the following error message: "The requested module 'franc' does not provide an export named 'default'." Unfortunately, I am unsure of what this means, despite trying to resolve ...

Can values from a dgrid store be saved in a variable or displayed in the console?

Currently, I am utilizing the dgrid store to display a grid (dgrid 0.4) on my website. Below is the code snippet that I have implemented: require([ 'dojo/_base/declare', 'dojo/Deferred', 'dstore/RequestMemory', ...

What is the proper method to trigger a re-render of a React functional component with the useEffect

Within my top-level component, I am utilizing a library to determine if a user’s browser is in light or dark mode. This information is then used to set the theme for the application, which includes HTML Canvas elements (it's crucial to note that the ...

Creating table structure dynamically using Node.js

I'm attempting to automatically create a table using nodejs "@google-cloud/bigquery": "^3.0.0" with the following approach: const bigqueryClient = new BigQuery(); schema = `driverId:string, passengerIds:(repeated string), pickedUp:(repeated s ...

What is the best way to hand off a component to a helper function?

I am trying to create a helper function in TypeScript that takes a component as an argument and returns an array of objects, each containing a component node... // helpers.ts import { LINKS } from '../constants'; // error on the next line: Cannot ...

I am unable to get JQuery UI Dialog to open on my end

Coding in HTML: <button type="button" class="btn btn-success" style="margin-bottom:14px" id="btnAdd" onclick="modaladdedit('URLToMyController')"><i class="fa fa-plus"> Add New</i></button> HEAD Tag Setup: <link rel=" ...