Sending data to another page in React Native can be achieved by passing the values as parameters

I am currently working on passing values from one page to another using navigation. I have attempted the following code:

this.props.navigation.navigate('welcome', 
{JSON_ListView_Clicked_Item:this.state.email,}))
in the parent class where I am sending it.
const { navigation } = this.props;
const JSON_ListView_Clicked_Item = 
navigation.getParam('JSON_ListView_Clicked_Item', 'NO-ID');
<Text>JSON_ListView_Clicked_Item: 
{JSON.stringify(JSON_ListView_Clicked_Item)}</Text>

This is the second class where I want the data to be displayed.

Here is my code:

this.state = { email: '', password: '', error: ''};
firebase.auth()
.signInWithEmailAndPassword(email, 
password).then(this.onLoginSuccess.bind(this))
.then(() => this.props.navigation.navigate('welcome', 
{JSON_ListView_Clicked_Item:this.state.emai

l,}))

Setting up the text input:

<TextInput
style={{height: 40,width:250,  borderRadius: 5  
,multiline:"true",borderColor: 'purple', 
borderWidth: 2,
}}
value={this.state.email}
secureTextEntry={false}
onChangeText={email => this.setState({ email })}
placeholder="email"
onSubmitEditing={() => {
this.focusNextField('Password');
}}
returnKeyType={ "next" }
ref={ input => {
this.inputs['email'] = input;
}} 
/>

Setting up the text input on the second class to retrieve the data:

renderComponent() {
const { navigation } = this.props;
const JSON_ListView_Clicked_Item = 
navigation.getParam('JSON_ListView_Clicked_Item', 'NO-ID');

if (this.state.loggedIn) {
return (
<View>

  <Text>JSON_ListView_Clicked_Item: 
{JSON.stringify(JSON_ListView_Clicked_Item)}</Text>
<Button
title="Sign out"
onPress={() => firebase.auth().signOut()} 

/>

</View>
);

Upon testing, I found that I am receiving blank data on the second page. My goal is to successfully pass the email when clicking the button on the first page.

Answer №1

import React from 'react';
import { Button, View, Text } from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation'; // Check package.json for version

class HomeScreen extends React.Component {

render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Welcome to the Home Screen</Text>
        <Button
          title="Go to Details"
          onPress={() => {
            /* Step 1: Navigate to the Details route with parameters */
            this.props.navigation.navigate('Details', {
              itemId: 86,
              otherParam: 'custom data here',
            });
          }}
        />
      </View>
    );
  }
}

class DetailsScreen extends React.Component {
  render() {
    /* Step 2: Retrieve and display the passed parameters */
    const { navigation } = this.props;
    const itemId = navigation.getParam('itemId', 'NO-ID');
    const otherParam = navigation.getParam('otherParam', 'default value');

return (
  <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
    <Text>Details Screen</Text>
    <Text>Item ID: {JSON.stringify(itemId)}</Text>
    <Text>Other Param: {JSON.stringify(otherParam)}</Text>
  </View>
);
  }
}

Here is an example demonstrating how to pass data to another page following these steps:

  1. yarn add react-navigation
  2. yarn add react-native-gesture-handler
  3. react-native link react-native-gesture-handler

You may also find the following resources helpful:

  1. Installation guide for React Navigation
  2. Guide on passing data in React Navigation

Answer №2

sender

       `this.props.navigation.navigate('Details', {
          itemId: 86,
          otherParam: 'anything you want here',
        });`

recipient

const { navigation } = this.props;
const itemId = navigation.getParam('itemId', 'NO-ID');
const otherParam = navigation.getParam('otherParam', 'some default value');

refer to the documentation for more information

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

Adjusting the transparency of numerous elements using JavaScript or jQuery

My task involves creating a large form where elements initially have an opacity of 0.5, and when a button is clicked, the opacity changes to 1.0. While I can achieve this using JavaScript, I want to find a more efficient way by avoiding individual if state ...

Implementing a function or template from one component into another within a Vue.js application, despite lacking a direct connection between the two components

Working on my Vue.js app, I encountered an interesting challenge: The layout of the app is simple: it consists of a header, a main view, and a navigation section at the bottom. Depending on the current page the user is on, I want to display a main action ...

NodeJS Jest test failing due to a global variable being set for a different test already

I am currently working on a project in TypeScript using Node.js and Jest. I have a function that may or may not modify a global variable, which is a TypeScript Map. After one test modifies the global variable, it retains that value for subsequent tests. I ...

How to conditionally prevent event propagation to children in VueJs

This Vue component is called ColorButtonGroup, and it serves as a group of checkbox/toggle buttons. It has a maximum limit of 4 colors that can be selected. The component utilizes another component called ToggleButton, which is a simple toggle selection w ...

What steps do I need to take to modify the MUI Badge component and insert custom text inside?

Is there a way to replace the number with a label next to a new row added to my table using MUI Badge? For example, instead of displaying a number like 4, I want it to show the word "New" as shown in this image: enter image description here This is the co ...

Checking the content of a textfield in React Material UI based on the user input

Hello! I am seeking a solution to trigger an error message whenever the value entered in the first text field is not equal to "28.71", otherwise display a correct message. Here is my current code: class Main extends React.PureComponent { render() { ...

Error: The function $.ajax(...).done(...).fail(...).complete does not exist

Out of nowhere, I started encountering the error message below: TypeError: $.ajax(...).done(...).fail(...).complete is not a function Below is my code snippet: this.sendRequest = function (type, extension, data, successCallback, successMsg, failMsg, ...

Implementing conditional dropdown menus with CodeIgniter

Explore the District Master Table: Dive into the District table: District Master District I need assistance with a form page that includes a Category dropdown. The district table stores district codes and category names. I want to display district names ...

Locate the positions of 2 identification numbers within a Mongoose array

I am currently working on developing a middleware that validates if a conversation exists between two users in the database. If the conversation does not exist, the middleware will create a new conversation. I am attempting to utilize Mongoose's $in o ...

Encountered a problem while trying to upload a video on bunny stream using node.js

Having trouble uploading videos to the Bunny Stream API using Node.js and Axios. Everything else seems to be working fine, like fetching, deleting, changing names, and resolutions of videos. However, when trying to upload a video, consistently receiving 40 ...

tips on displaying a div dynamically in a specific location

Currently, I have implemented HTML textBoxes on my website. However, I am looking to validate these textBoxes using JavaScript. Rather than displaying a traditional alert popup for invalid data input, I would like to show a div next to the specific textBox ...

Is there a way to remove the initial number entered on a calculator's display in order to prevent the second number from being added onto the first one?

I am currently in the process of developing a calculator using HTML, CSS, and JavaScript. However, I have encountered an issue with my code. After a user inputs a number and then clicks on an operator, the operator remains highlighted until the user inputs ...

Angular2 Navigation Menu

I have a side bar and I want its children to appear when the user clicks on the parent. For example, clicking on LinkTest should display its corresponding content as block. You can check out the Angular and Typescript code snippet at this link: http://jsfi ...

What is the method for retrieving array elements within an object?

I have an array filled with multiple objects, each containing their own array of sub-objects. My objective is to iterate through the "subMenuItems" array within each object and display the values inside. Here's the Array I'm working with: export ...

Leveraging Enjoyhint within nextJS

I am attempting to create a code tour using EnjoyHint, but encountered an error after installing the xbs-enjoyhint library. The error reads: Server Error - ReferenceError: CanvasRenderingContext2D is not defined. This issue is within the jquery.enjoyhint ...

Add three rows without clicking, then click once to add one row at a time

Seeking guidance on how to defaultly display 3 rows after adding and removing rows, as well as applying the removal of a default set of 3 rows using JavaScript. Any valuable ideas are appreciated! Example needed:- $(document).ready(function (){ ...

Leveraging the source of an image from asset variables

Lately, I've been experiencing issues with displaying images on my page, specifically when trying to show a list of images. The problem arises when attempting to store the image URL in a variable or object instead of hardcoding it directly into the s ...

the angular variable scope has not been defined

Currently, I am developing an angular controller that is configured to utilize the "controller as" syntax: angular.module('app', []).controller('ctrl1', ctrl1); ctrl1.$inject = ['$http', '$compile']; function ctrl ...

Using Angular JS for Traditional Multi-page Websites

Lately, I've been diving into Angular 2 and I have to admit, it's an impressive framework for building single-page applications. But here's the thing - how would one go about integrating Angular with a traditional website (maybe using codei ...

IE encounters issues making Ajax calls when transitioning from secure HTTPS requests to insecure HTTP requests

I am currently facing an issue with my ajax CORS request. It is functioning perfectly on all browsers except for Internet Explorer. In IE, the request doesn't even attempt to go through and fails instantly without any error messages appearing in the c ...