The error message "navigation.navigate is not a function" is encountered while working with React Native

I encountered an issue with navigation in my React application. The error message "undefined is not an object (evaluating 'navigation.navigate')" appears when attempting to navigate to another screen using a button from a different route.

Here is the component code:

     export default function Structures({ title, display, navigation }) {
      const [structures, setStructures] = useState([]);
    
      useEffect(() => {
        async function loadStructures() {
          const response = await api.get('/product/api/structures');
    
          setStructures(response.data);
        }
        loadStructures();
      }, []);
    
    
      return (
...
   
          <ProductList>
            {structures.map(structure => (
              <Item key={structure.id} onPress={()=> navigation.navigate('Orders')}> 
...

And here is the routes code:

const Tab = createMaterialBottomTabNavigator();
function MyTabs(){
    return(
        <Tab.Navigator
        barStyle={{ backgroundColor: '#694fad' }} 
        initialRouteName='Feed'   
        activeColor='black' 
        >
            <Tab.Screen 
                name="Home"
                component={Dashboard}
                options={{
                    tabBarLabel: 'Home',
                    tabBarIcon: ({ color }) => (
                      <MaterialCommunityIcons name="home"  size={26} />
                    ),
                  }}
            />
            <Tab.Screen 
                name="Orders"
                component={Requests}
                options={{
                    tabBarLabel: 'Orders',
                    tabBarIcon: ({ color }) => (
                      <MaterialCommunityIcons name="assignment"  size={26} />
                    ),
                  }}
            />
        </Tab.Navigator>)}

export default function Routes() {      
    return (
      <NavigationContainer>
        <MyTabs />
      </NavigationContainer>
    );
  }

I attempted using Stack navigation as well, but the same error persisted.

Answer №1

Only the immediate child of your navigator stack can access the navigation prop. It appears that your component Estruturas is not a direct route, so it won't receive the navigation prop directly in its function props. There are two solutions to resolve this issue.

  • You can either utilize the withNavigation HOC provided by react-navigation v4 or, if you are using v5, you can use the useNavigation hook.
  • Alternatively, you can pass the navigation prop to the component wherever you instantiate it. This can be achieved as shown below:-

export default function Dashboard(props) {
  return (
    <View>
      <Estruturas navigation={props.navigation} />
    </View>
  );
}

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

Exposing the full binary in jQuery

Can anyone explain how jQuery can display the entire binary representation of a number without removing the leading zeros? Here is the code snippet: HTML: <input id="input" type="text" size="20"> <input id="result" type="text" size="30"> < ...

`I'm experiencing issues with my AJAX call when using Django`

As part of my blog practice, I'm trying to ensure that all notifications are marked as seen when a user views them. This functionality works fine when I manually go to the URL, but it's not working when using Ajax. Here is the JavaScript code: ...

Indicator malfunctioning on Carousel feature

I created a carousel containing six photos, but I am encountering an issue with the carousel indicators below. The first three indicators work correctly – when clicked, they take me to the corresponding slide (e.g., clicking the 1st indicator takes me ...

Click Action on CanJS Table

I am currently developing a canJS application and have been able to successfully handle the click event for an HTML table using the code below. 'table td click':function(el,event){ console.log('clicked ',el.text()); } ...

"Nested AngularJS controllers: a deep dive into the world

Recently, I've been delving into the world of AngularJS and I can't shake the feeling that my approach to the paradigm might be a bit off. I have a controller for managing panes (linked to an ng-repeat) which tracks which panes the user has open ...

The issue of selecting multiple classes simultaneously is not being resolved

Here is my JavaScript code snippet: $('.normal-box').click(function(){ //unique row id var id = $(this).data('row-id'); //its index according to the content array var index = $(this).data('index'); //which car ...

The reason for the issue stating 'ReferenceError: xmlHttpRequest is not defined' is likely due to the presence of certain IDs

Basically, I am trying to insert values into my database using Ajax in a WordPress custom template called company-update/?update=. This way, the page will not refresh and each record can be inserted individually. I have created a form along with JavaScrip ...

Troubleshooting AngularJS ng-route and Three.js crashes and glitches: A comprehensive guide

I am currently working on a website that utilizes angularjs along with the ng-route directive for navigation between different views. The site also incorporates Three.js for WebGL rendering on canvas. However, I am encountering difficulties as the applicat ...

Update destination upon click

I'm new to JavaScript and attempting to modify a redirect link using checkboxes that will modify the URL, followed by a button that will use the updated URL. However, I'm facing some challenges with my code and could use some guidance. Here is t ...

Go back to the previous selection in the Select field if the JavaScript Confirm function returns a false value

I am dealing with an HTML select field that has one option pre-selected. Whenever another option is selected, a change event is triggered which displays a confirmation prompt. What I am trying to achieve is, if the user cancels the confirmation (i.e., if ...

The XML data is valid, however the responseXML property in the XMLHttpRequest response is null

Click here to access the API URL, which returns XML data. However, the responseXML property in the XMLHttpRequest response is coming back empty. How can I retrieve the XML data from the response? document.body.onload = loadXMLDoc(); function loadXMLDoc ...

There has been an issue with parsing the JSON file due to an invalid character found at

I keep encountering a parse error whenever I attempt to send a post request to the server. $.post("../php/user_handler.php", formData, function(data) { var result = JSON.parse(data); if(result.status === 'error') { ...

Leverage AJAX on the client-side for optimal performance while utilizing node.js

I am currently working on a simple nodejs application that displays HTML pages. Within this application, there are two buttons that are linked to JavaScript functions in separate files. One of the functions uses ajax, while the other does not. However, I a ...

Is it possible to utilize Babel for transpiling, importing, and exporting in the client, all without relying on Web

Is it possible to compile JSX and export variables through the global namespace using Babel? I'm not interested in setting up a Webpack server. I'm currently familiarizing myself with ES6, JSX, Babel, and React, and I find adding another librar ...

The specified file ngx-extended-pdf-viewer/assets/pdf.js cannot be found

I have integrated the ngx-extended-pdf-viewer package in my Angular application using npm to enable the display of PDF content. According to the setup instructions, I have added the following configuration in my angular.json file: "assets": [ ...

Functional React component using a stateless class within

I need some valuable suggestions for a specific scenario. I am interested in developing my own Datetimepicker react component. I have been exploring different codes to easily create a calendar and came across a Regular Class that generates the calendar. M ...

How can CORS be activated? Is it through the server or Javascript, and where does this

Currently, I am testing my ReactJS website on localhost:3333 and my ASP.NET Web API 2 on localhost:54690. I am utilizing axios for my AJAX requests, but encountering an error when making a request. XMLHttpRequest cannot load http://localhost:54690/api/ ...

Issue with box shadow appearing incorrectly as element content increases in size while the body has an image background

After applying a box shadow to the header div, I noticed that the box shadow doesn't display properly when the hidden elements within the header are revealed. <div id="header"> <div id="logo"> <a href="#"><img src="logo.png" ...

Exploring a different method for implementing animations during UI-router state transitions

My product owner presented me with a seemingly impossible challenge to create animations between states. I utilized ngAnimate and thought I had a brilliant solution - only to be told it wasn't what they wanted. "This isn't what I had in mind," h ...

What is the best way to apply an "active" class to the images that are displayed depending on the object's properties?

Below is a link to the JSON file I am working with - The JSON file consists of 5 main categories of runes, with each category containing 4 slots. Each slot has 3 runes, except for the first slot which has 4 runes. The code snippet below loops through the ...