The object does not contain a 'navigation' property within the 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' type

As a beginner in react native, I am facing some challenges with the components I have created. Let me share them:

List of Playlists:

export default class Playlists extends Component {
  playlists = [
    ...
  ];

  render() {
    const {navigation} = this.props.navigation;

    return (
      <FlatList
        data={this.playlists}
        renderItem={({item}) => (
          <TouchableOpacity
            style={styles.item}
            onPress={() => navigation.navigate('PlaylistDetails', item)}>
            <Text style={styles.text}>{item.name}</Text>
          </TouchableOpacity>
        )}
      />
    );
  }
}

View for Playlist Details:

export default class PlaylistDetails extends Component {
  render() {
    const {navigation} = this.props.navigation;
    var songs: Song[] = navigation.getParam('songs');

    return (
      <View>
        <Text>{navigation.getParam('name')}</Text>
        <FlatList
          data={songs}
          renderItem={({item: song}) => <Text>{song.title}</Text>}
        />
      </View>
    );
  }
}

Navigation setup:

const screens = {
  Playlists: {
    screen: Playlists,
  },
  PlaylistDetails: {
    screen: PlaylistDetails,
  },
};

const stack = createStackNavigator(screens);

export default createAppContainer(stack);

However, I encountered an error at

const { navigation } = this.props.navigation;
, showing
Property 'navigation' does not exist on type ...
.

To resolve this, I attempted to define an interface:

interface Props {
    navigation: any
}

And then used it in the component as follows:

export default class PlaylistDetails extends Component<Props> {
    ...
}

Although this fixed the errors, I now face a new issue when running the application:

TypeError: undefined is not an object (evaluating 'navigation.navigate')
.

Being new to react native, I am unsure how to address this problem. Any help or advice would be greatly appreciated.

Answer №1

Everything looks good, and you have correctly defined the interface.

One suggestion is to spread the props instead of going one level deep and spreading the navigation property within the props object.

Here's the revised code:

export default class PlaylistDetails extends Component<Props> {
  render() {

    // Update this: 
    const { navigation, ...otherProps } = this.props;
    var songs: Song[] = otherProps.navigation.getParam('songs');

    return (
      <View>
        <Text>{otherProps.navigation.getParam('name')}</Text>
        <FlatList
          data={songs}
          renderItem={({item: song}) => <Text>{song.title}</Text>}
        />
      </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

Background Patterns on Webpages

My website has a lovely gradient background on the html tag in css, while the body tag showcases a seamless pattern repeating on both the x and y axes. Everything was looking great until I checked the website on an iPad/iPhone in portrait mode, where the ...

Preventing users from accessing the previous page via the browser back button after logging out in an AngularJS application

Currently, I have developed an angularjs web application and facing a challenge. After logout, I am looking to prevent users from navigating back to the previous page using the browser's back button. Ideally, I would like to display a customized messa ...

Utilizing Captcha with Meteor's accounts-ui-bootstrap-3 for enhanced security

Is it possible to incorporate Captcha verification when utilizing the combo of Meteor packages accounts-ui-bootstrap-3 and accounts-password? What is the process for integrating a package such as captchagen with accounts-ui? ...

Halt the CSS transition on the preceding element

I tried to pause a CSS transition and came across a question with a solution that seems similar: Is there a way to pause CSS transition mid-way? However, I couldn't make it work for my code. I suspect the issue lies with the before element. What cou ...

Tips on transmitting JSON data from a Spring controller to JavaScript

Does anyone have experience with sending a JSON object from a spring controller to JavaScript and receiving it using AJAX? I would appreciate any guidance on how to accomplish this. ...

Why won't the CSS update in Next.js when the local state variable changes on page load?

I seem to be facing an issue with a variable stored in localStorage that changes when using a toggle button. The color changes correctly upon toggling the button, but upon page refresh, it doesn't display the correct color saved in local storage. Eve ...

Looking to incorporate AAD calling functionality in a React and Node application by utilizing the Graph API for communication/calls

As a newcomer to Microsoft Azure and its services, I recently registered an application with Azure. However, when attempting to integrate a call feature in my Web App using the graph API '/communication/calls', I encountered the following error m ...

What is the best way to identify the clicked cell?

I'm a JavaScript newbie trying to work with ExtJS 3.4. I've set up a basic tree with 3 columns and now I want to figure out which cell, row, or column has been selected. Currently, I'm following the example provided by Sencha at : var tr ...

An assortment of the most similar values from a pair of arrays

I am seeking an algorithm optimization for solving a specific problem that may be challenging to explain. My focus is not on speed or performance, but rather on simplicity and readability of the code. I wonder if someone has a more elegant solution than mi ...

Developing a function that takes a parameter which can be used with or without an additional argument when invoked

In my React application, I have a method that accepts a parameter for displaying a modal. const displayModal = (p:Result) => { setConfirm(true); if(p) { //check variable for truthy setSelectedRow(p); } ...

ExpressJS route handler encounters an error due to undefined 'this' reference

teamList.js class teamListCtrl { constructor() { this.data = "example"; } fetch(response, request) { console.log("DISPLAY ! ", JSON.stringify(this)); } } module.exports = new teamListCtrl(); //singleton router.js var express = require( ...

Issue with selecting a value in React MUI and default value not being defined

Currently, I am working on creating a form in React using MUI and Formik. While implementing the select feature with default values fetched from an API object, I encountered issues where the select function was not working as expected. Strangely, I couldn& ...

Sending input values through an identifier within a pop-up dialog box

Struggling with my jQuery and Ajax skills, especially when it comes to editing data. The add method works fine, but the edit functionality is giving me trouble. I have a route for editing like /edit/{id}, and whenever I click the button in the modal, it ...

Having trouble populating and submitting a selected option from a dropdown menu in Angular?

Upon loading the page, the Category dropdown automatically populates with data from the database. However, when I attempt to select a value from the dropdown and click a button to post the data to a specified URL, an error occurs: ERROR Error: Error tryin ...

Retrieving journal web addresses using the CORE API

I am currently working on pulling journal data from the CORE API in React, specifically focusing on obtaining the title and URL of each journal. My goal is to create clickable links that direct users to the specified URLs. { "identifiers": [ ...

How can you handle undefined values in the query object parameter when using Mongoose's Find function?

Alright: Sound.find({ what: req.query.what, where: req.query.where, date: req.query.date, hour: req.query.hour}, function(err, varToStoreResult, count) { //perform some actions }); Let's consider a scenario where only req.query.what has a ...

Angularjs: The Art of Loading Modules

I am facing an issue while trying to load certain modules. controller1.js: angular.module('LPC') .controller('lista_peliculas_controller', ['$scope', function($scope) { $scope.hola="hola peliculas"; }]); And ap ...

Tips for saving data to a file using the frontend

Is it possible for draw.io to write directly to a local file from my browser without the need for any server app or browser extension? I'm not referring to simply downloading a file, but actually writing to a file. For example, when creating a new dia ...

Moving files by dragging and dropping rather than deleting them

I have successfully implemented a feature using JavaScript to drag and drop multiple files, followed by displaying those images. The code below is fully functional without any errors. Need help with: I am now looking to add the ability to remove these ima ...

Tips for selecting a JSON data node on-the-fly using jQuery

This is an example of my ajax function: $.ajax({ type: "GET", dataType: "json", async: false, url: "/wp-content/comment_data.php", data: 'songid=' + $array, success: function(data){ oTable.find('td').eac ...