Having difficulty transferring navigation props between screens using react-navigation

Within my ContactList component, I have utilized a map to render various items. Each item includes a thumbnail and the desired functionality is that upon clicking on the thumbnail, the user should be directed to a new screen referred to as UserDetailsScreen. Furthermore, during this navigation process, specific data related to the selected user should also be transferred to the subsequent screen.

The usage of modals proved ineffective in this scenario due to the possibility of multiple modals opening concurrently when integrated within a map structure. Therefore, an alternative approach involving react-navigation is being explored.

In ContactList.tsx:

export const ContactList: React.FunctionComponent<UserProps> = ({
  data,
  onDeleteContact,
}) => {
  const [isUserVisible, setIsUserVisible] = useState(false);
  //const [visibleUser, setVisibleUser] = useState<any>();
  const navigation = useNavigation();

  return (
    <View style={styles.users}>
      {data.users.nodes[0].userRelations.map(
        (item: { relatedUser: RelatedUser; id: number }) => {
          const numberOfFriends = item.relatedUser.userRelations.length;
          const numberPlate = 'WHV AB 123';
          return (
            <View style={styles.item} key={item.id}>
              {/* <TouchableOpacity onPress={() => setIsUserVisible(true)}> */}
              <TouchableOpacity
                onPress={() =>
                  navigation.navigate('UserDetailsScreen', {
                    firstName: item.relatedUser.firstName,
                    rating: item.relatedUser.rating,
                    numberOfFriends: numberOfFriends,
                    onDeleteContact: onDeleteContact,
                    isUserVisible: isUserVisible,
                    setIsUserVisible: setIsUserVisible,
                    numberPlate: numberPlate,
                    navigation: navigation,
                  })
                }>
                <Thumbnail
                  }}></Thumbnail>
              </TouchableOpacity>
              <View style={styles.nameNumber}>
                <Text style={styles.userName}>{userName}</Text>
              </View>
              {/* <UserDetails
                firstName={item.relatedUser.firstName}
                rating={item.relatedUser.rating}
                numberOfFriends={numberOfFriends}
                onDeleteContact={onDeleteContact}
                isUserVisible={isUserVisible}
                setIsUserVisible={setIsUserVisible}
                  numberPlate={numberPlate}>
                </UserDetails> */}
            </View>
          );
        },
      )}
    </View>
  );
};

Regarding UserDetailsScreen:

type UserProps = {
  //data: UsersQueryHookResult,
  firstName: string;
  rating: number;
  numberOfFriends: number;
  numberPlate: string;
  onDeleteContact: (id: number) => void;
  navigation: any;
};

export const UserDetailsScreen: React.FunctionComponent<UserProps> = ({
  firstName,
  rating,
  numberOfFriends,
  numberPlate,
  onDeleteContact,
  navigation,
//   isUserVisible,
//   setIsUserVisible,
}) => {
//const navigation = useNavigation();
const fName = navigation.getParam('firstName')
  return (
    // <Modal visible={isUserVisible}>
      <View style={styles.container}>
        <View>
          <TouchableOpacity
            style={styles.cross}
            //onPress={() => setIsUserVisible(false)}>
              onPress={() => navigation.navigate('Whitelist')}>
            <Thumbnail></Thumbnail>
          </TouchableOpacity>
        </View>
        <View style={styles.searchLocationContainer}>
          <UserInfoContainer
            firstName={firstName}
            rating={rating}
            numberPlate={numberPlate}
            numberOfFriends={numberOfFriends}></UserInfoContainer>
        </View>
      </View>
    // </Modal>
  );
};

Furthermore, it is imperative that upon clicking the thumbnail from the aforementioned screen, the user can navigate back to the initial screen enabling the selection of another object.

A common issue faced revolves around errors pertaining to navigation.getParam being undefined. How can such issues be resolved?

One potential solution involves utilizing the route props; however, uncertainty prevails regarding their implementation and whether they should be passed within both screens or solely one.

Answer №1

retrieve information from route props

for example

type UserInformation = {
  // data: UsersQueryHookResult,
  firstName: string;
  rating: number;
  numberOfFriends: number;
  numberPlate: string;
  onDeleteContact: (id: number) => void;
  navigation: any;
  route: any;
};

export const UserDetailsScreen: React.FunctionComponent<UserInformation> = ({
  firstName,
  rating,
  numberOfFriends,
  numberPlate,
  onDeleteContact,
  navigation,
  route,
//   isUserVisible,
//   setIsUserVisible,
})....
route.params.firstName

if you are able to navigate to UserDetailsScreen then passing a route is not necessary because navigation and its properties are already set within UserDetailsScreen

Answer №2

Your approach to passing parameters to UserDetailsScreen is accurate.

In older versions of react-navigation (1.x to 4.x), you could access params using "navigation.state.params".

With react-navigation 5, they have made changes to how this is done. Parameters are now accessed through the "route.params" object when passed to your screen or component. See the example code below for more information:

type UserProps = {
    route: any,
    navigation: any,
};

export const UserDetailsScreen: React.FunctionComponent<UserProps> = ({
    route, navigation
}) => {
    const {
        firstname,
        rating,
        numberOfFriends,
        numberPlate,
        onDeleteContact,
    } = route.params;
    
    return (
        <View style={styles.container}>
            <View>
                <TouchableOpacity
                    style={styles.cross}
                    //onPress={() => setIsUserVisible(false)}>
                    onPress={() => navigation.navigate('Whitelist')}>
                    <Thumbnail />
                </TouchableOpacity>
            </View>
            <View style={styles.searchLocationContainer}>
                <UserInfoContainer
                    firstName={firstName}
                    rating={rating}
                    numberPlate={numberPlate}
                    numberOfFriends={numberOfFriends}
                />
            </View>
        </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

The use of multiple Where clauses in a Firestore Firebase query is not functioning as expected when implemented in JavaScript code

https://i.stack.imgur.com/DdUGj.png db.collection('User_Info').where("User_Name", "==", "Sam").where("PASSWORD", "==", "c2FtMTIzQA==").get().then(snapshot => { if(snapshot.docs.length > 0 ){ debugger; alert("Login Successful."); ...

When trying to authorize my channel, the JSON data is coming back as a blank string

I've encountered an issue with my JavaScript code: Pusher is throwing the error message "JSON returned from auth endpoint was invalid, yet status code was 200. Data was: ", indicating empty data. I have double-checked the broadcasting service provider ...

When IntelliJ starts Spring boot, resources folder assets are not served

I'm following a tutorial similar to this one. The setup involves a pom file that manages two modules, the frontend module and the backend module. Tools being used: IDE: Intellij, spring-boot, Vue.js I initialized the frontent module using vue init w ...

Is the sudden disconnection from Chrome after a WebSocket handshake related to a domain mismatch or is it possibly a bug in Chrome?

I created my own WebSocket server using Python, but I encountered an issue where Chrome 4.0.249.78 dev (36714) always disconnects after the handshake process. Wanting to rule out any issues with my code, I tested it using the WebSocket server from , only t ...

Can you explain the purpose of the CssBaseline class?

I'm curious about the purpose of the CssBaseline class in the Material-UI React library. I've searched online but couldn't find a clear answer, and the page I linked to doesn't offer much information either. Can anyone explain what this ...

Issue with BlobUrl not functioning properly when included as the source in an audio tag

I need help with playing an audio file on click. I tried to implement it but for some reason, it's not working as expected. The response from the server is in binary format, which I decoded using base64_decode(responseFromServer); On the frontend (Vu ...

Function in Node.js/JavaScript that generates a new path by taking into account the original filepath, basepath, and desired destination path

Is there a custom function in Node.js that takes three arguments - filePath, basePath, and destPath - and returns a new path? For example: Function Signature Example var path = require('path'); // Could the `path` module in Node be useful here? ...

A guide on customizing the color of the icon in Material UI's NativeSelect component

I am using a NativeSelect component. <NativeSelect input={<BootstrapInput/>} onChange={this.handleClick} > <option value="1">1</option> <NativeSelect> Is there a way to customize the color of the dropdown button in Nat ...

Create a list using ng-repeat in AngularJS, each item separated by "custom categories"

I am looking to create a dynamic list that will display values entered by users, categorized by custom categories. The challenge is that I do not know in advance which category each element will belong to. Here's an example of how I envision the list ...

Why does it seem like only one div is being added?

I am facing an issue with dynamically appending multiple div elements. Despite my efforts, only one div element is showing up on the browser when I try to test the code. I have searched for similar problems but could not find any solutions. Any assistanc ...

Issues with JQuery Ajax rendering in browser (suspected)

I'm encountering an issue on my webpage. I have a div with two hidden fields containing values of 0 and 2, respectively. Upon clicking a button that triggers an AJAX query, the div contents are updated with hidden field values of 1 and 2. However, it ...

Parsing and Displaying JSON Data from a Python DataFrame in D3

Trying to create a stock chart, I encountered an issue with parsing the json file output by my python dataframe. The example code from http://bl.ocks.org/mbostock/3884955 does not seem to fit the format of my data: The json looks like this: var dataset = ...

The gradual disappearance and reappearance of a table row

I am struggling with making a row fade out when a specific select value is chosen (such as "termination"), and fade in when any other option is selected. The code works perfectly fine when the div ID is placed outside the table, but once I encapsulate it w ...

Building a React Router application hosted on an Nginx server

I have an application with two routes: home and results. When navigating from the home page to our authorization microservices and then back to my React app on the result page, I encounter a 404 error because the result.html file does not exist in a React ...

Passing an undefined value to the database via AJAX upon clicking a button

Hi there, I'm currently working on a table where I'm trying to perform an inline edit and update the value in the database by clicking on a button (an image). I've attempted to use an onclick function, but it seems to show "value=undefined&a ...

Send binary information using Prototype Ajax request

Currently, I am utilizing Prototype to send a POST request, and within the postdata are numerous fields. One of these fields contains binary data from a file, such as an Excel spreadsheet chosen by the user for upload. To retrieve the contents of the file ...

Problem with React Router: Uncaught Error - Invariant Violation: The element type is not valid, a string is expected for built-in components

I am encountering an issue with react-router and unable to render my app due to this error. Here is a screenshot of the error I have searched extensively for a solution but have not been able to find anything useful. Any help would be greatly appreciated ...

Issues with React Native imports not functioning properly following recent upgrade

Hey there, I’ve been tasked with updating an old React-Native iOS project from version 0.25.1 to 0.48.0. However, I’m encountering several compiler issues and struggling to navigate through the code updates. The project includes an index.ios.js file s ...

What is the best way to mix up the middle letters within certain positions of a word?

Here is what I have managed to achieve so far: mounted() { const randomVariants = [...Array(3)].map(() => this.baseWord .split('') .sort(() => 0.5 - Math.random()) .join('') ) const variantsWithoutIniti ...

Is it possible to determine the number of JSON properties without the need for a loop?

I have a question about organizing data. I have a vast amount of data with various properties, and I am looking for a way to display each property along with how many times it occurs. For example: 0:[ variants:{ "color":"blue" "size":"3" } ] 1 ...