Tips for sending information back to the previous screen in React Native Navigation version 5

Recently, I upgraded to react native navigation version 5 and now I am facing an issue with sending data back to the previous screen when making a goBack() call.

To navigate to the next view, I use:

const onSelectCountry = item => {
    console.log(item);
};

navigation.navigate('SelectionScreen', {
        onSelect: onSelectCountry});

After selecting an item from FlatList, I try to go back by using:

function onSelectedItem(item) {
    route.params.onSelect(item);
    navigation.goBack();
}

However, I get a warning about non-serializable values in the navigation state when sending functions as params. Can someone guide me on the correct way to achieve this?

Answer №1

Here is a sample implementation:

Screen A

const DisplayScreen1 = ({navigation, route}) => {
  const [selectedItem, setSelectedItem] = useState(null);

  useEffect(() => {
    navigation.addListener('focus', () => {
      console.log(route.params)
    })
  }, [])  

  const handleClick = () => {
    navigation.navigate('DisplayScreen2', {onUpdate: (selected) => {
      setSelectedItem(selected)
    }})
  }
  return (
    // Render components for Screen 1
  )
}

Screen B:

const DisplayScreen2 = ({navigation, route}) => {

  useEffect(() => {
    navigation.addListener('focus', () => {
      console.log(route.params)
    })
  }, [])  

  const handleBackPress = () => {
    route.params.onReturn(selectedItem);
    navigation.goBack()
  }

  return (
    // Render components for Screen 2
  )
}

Answer №2

transferring information to various screens through navigation.

onPress={() => {
          // Sending parameters back to the main screen
          navigation.navigate('Home', { post: postText });

refer to the official guide at React Native documentation

Answer №3

I found myself drawn to this post because I needed to incorporate a common component into 2 different stacks. How can I efficiently navigate between the two and pass necessary parameters?

The solution I discovered involved initially passing a parameter to indicate the origin of component access. Instead of relying on goBack(), which doesn't support parameters, I opted to navigate to the previous route and include the parameter.

//within Stack1
navigation.navigate('commonComponent', isStack1: true)
//inside Stack2
navigation.navigate('commonComponent', isStack1: false)
//within CommonComponent - utilize navigation.navigate instead of goback()

function CommonComponent({ navigation, route }) {
  const {isStack1} = route.params
  const customRoute = isStack1 ? 'routeNameInStack1' : 'routeNameInStack2'
  return (
    <Button title="Go back" onPress={() => navigation.navigate('customRoute', {myParams: 'blabla...'}) />
  )
}

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

What is the best way to execute an Nx executor function using Node.js?

Can a customized Nx executor function be executed after the app image is built? This is the approach I am taking: "migrate-up": { "executor": "@nx-mongo-migrate/mongo-migrate:up", "options": { &q ...

Creating a worldwide directive using AngularJS

I'm currently working on implementing a directive that will manage user interaction with the navigation system on my website. The directive includes an element.click event listener in the link function, which is responsible for toggling the display of ...

Connecting buttons to JavaScript functions that interact with MySQL database entries

I am working on a task involving rendering a database table using XMLHttpRequest in JavaScript to a PHP page. My goal is to display each entry from the table as an HTML row/cell with two buttons within each "entry". These buttons should trigger specific Ja ...

Intersection Observer API is not compatible with the functionality of the navigation bar

Having trouble with the Intersection Observer API. Attempting to use it to show a nav-bar with a white background fixed to the viewport once it scrolls out of view. Initially tested using console.log('visible') successfully to determine visibili ...

AngularJS directive for jQuery Handsontable is a powerful tool for creating interactive

I've been experimenting with using jQuery handsontable in conjunction with an angular directive, but I've encountered a strange issue. Whenever I type something into the cells, the characters appear outside of the table instead of inside it. Oddl ...

Looping through a set of API calls using JavaScript Web API

Currently, I am in the process of developing an application using angularjs and ionic. Within this app, I have an array containing IDs, and my objective is to retrieve their corresponding names. To achieve this, I attempted the following code snippet: var ...

Managing all AJAX success events in one centralized location using jQuery

In a particular situation, I find myself needing to handle all jquery success events in one centralized location. This is because I want a specific function to be called after every ajax success event occurs. While I am aware that I can use $.ajaxComplete ...

Ensuring the script waits for the complete loading of iframe prior to

I'm faced with an issue on the website I'm currently working on. There's a Live Chat plugin integrated on an iframe, and I need to change an image if no agents are available. Interestingly, my code works perfectly fine when tested on the con ...

elementToBeClickable is not supported by webdriverio

I am having some trouble with the 'waitForEnabled' function as it does not seem to behave like Webdriver's elementToBeClickable. Is there anyone who can provide some guidance on how to use this API effectively? ...

jquery selector to target an element nested inside an anchor tag

Is there a way to use a Jquery selector to extract the text content within the 'name' attribute? <a href="page1.php" id='title' name="<?php echo $res['id'];?>" title="<?php echo $res['title'];?>" < ...

Save pictures in MongoDB using GridFS or BSON format

As a newcomer to MongoDB, I am seeking advice on the best way to store images in the database. Gridfs and BSON seem to be the most common options, but I'm unsure about their respective pros and cons. The main difference I'm aware of is the 16MB s ...

The header location functionality is not functioning properly on the live server

I have a single registration and payment page where the program flow goes from registration to confirmation and then to payment. Upon validation and calculation on the registration page, it should redirect to the confirmation page. This is my code: < ...

Focus Google Map on Selected Option using AngularJS

I'm attempting to center the map based on a selection in a drop-down select option box. Despite trying various examples, I haven't been successful in getting the map to recenter to the new latitude and longitude coordinates. I'd like to ach ...

Creating a Dynamic Input Validation Range with JQuery

Greetings and thank you for taking the time to review this! :-) The form validation is functioning correctly with required fields, but I am facing a challenge with setting up numeric range validation dynamically for an autocomplete feature. The JQuery val ...

Guide on setting a wait while downloading a PDF file with protractor

As I begin the download of a pdf file, I realize that it will take more than 2 minutes to complete. In order to verify if the file has successfully downloaded or not, I will need to wait for the full 2 minutes before performing any verification checks. C ...

How can I fully mock a component in an Angular Unit Test, rather than just a single class?

In my current task, I am faced with the challenge of unit testing a component that relies on a subcomponent. The subcomponent utilizes CanvasJS for displaying plots, but this poses issues when running Jest Unit Tests. As of now, in my spec file, the follo ...

Having trouble configuring Jest for TypeScript integration

I am currently implementing unit testing for a typescript project following the guidelines in this example: https://dev.to/muhajirdev/unit-testing-with-typescript-and-jest-2gln In my project, I have a file named main.ts that exports an isInternalLink func ...

What is the process for using the scrollIntoView function on an svg element like a rectangle?

I have a graph panel with an SVG. The nodes in the SVG are listed in a separate panel. I would like for when a node is clicked in the node list, the SVG will scroll to that specific node. Each node is represented by a rectangle shape. However, I noticed th ...

Exporting third party definitions from a TypeScript npm module for reuse in other projects

Our custom npm logging module, which is built using TypeScript and relies on the pino library, encounters errors when being imported into an application: Error: node_modules/@scope/logging/lib/index.d.ts(1,23): error TS2688: 'pino' type definiti ...

What is the best way to assign or convert an object of one type to another specific type?

So here's the scenario: I have an object of type 'any' and I want to assign it an object of type 'myResponse' as shown below. public obj: any; public set Result() { obj = myResponse; } Now, in another function ...