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

What is the best way to open a browser window at a quarter of its default size?

Is there a way to open a window at 25% of its default device browser window size? I attempted the code below, which worked. However, it only accepts pixel inputs and not relative % values. This makes it non-scalable across various devices. window.resizeT ...

Issues with changing background colors using Jquery animate

I am attempting to create a fading background color effect when a button is clicked. Currently, I can change the background color using this code: $("#" + lblqty).css("background","#e9f1ff"); However, when I try to use the animate function as shown below ...

Access to a custom Google Map via an API connection

I currently have multiple custom Google Maps that I created using and they are all associated with my Google account. Is it possible to access these maps using the Google Maps JavaScript API? It seems like the API does not work with manually created maps ...

What is the best way to retrieve the updated value following a mutation in Vuex?

In my Vuex module, I have a simple setup for managing a global date object: import moment from 'moment'; const state = { date: moment() } // getters const getters = { date: state => state.date, daysInMonth: state => state.dat ...

Javascript cards arranged in descending order

I'm in the process of developing a sorting feature that arranges cards in the DOM from Z to A with the click of a button. Although I've successfully implemented the logic for sorting the array, I'm facing difficulties in rendering it. Withi ...

Apache causes HTML download tag to malfunction

I have an HTML file that includes the following code: <a href="/Library/WebServer/Documents/file.zip" download="file.zip"> Download here </a> When I test this HTML page on Chrome, it successfully allows me to download the file. However, when ...

Keep elements in position when their bottom edge becomes visible while scrolling

This task may appear intricate, but I will do my best to explain it! I want to create a continuous scrolling article display similar to Bloomberg Politics (), but with a slight twist. My idea is to have the current article's bottom edge stick to the ...

Is there anything else I should attempt in order to fix this npm start error?

I have been troubleshooting this issue by researching other stack overflow posts, but I continue to encounter the same error message repeatedly. My goal is to execute a Javascript program that incorporates ReactJS. Initially, everything was functioning sm ...

Tips for modifying CSS when a user scrolls beyond a specific div

Currently, I am working on implementing a scroll function that dynamically moves elements based on the user's scrolling behavior. The code I have written works to some extent and successfully moves the elements. However, my goal is to create a list o ...

Designing a Dynamic Floating Element that Shifts with Scroll Movement

Hey there everyone!, I am currently working on a project in Wordpress and I was wondering if anyone has experience creating a floating widget that moves along with the page as you scroll. Any suggestions on how to achieve this? Would it involve using Javas ...

Tips for preventing the unmounting of child components while utilizing JSX's map function

This is a condensed version of a question I previously asked. Hopefully, it's clearer and more comprehensible. Here is a simple application with 3 input fields that accept numbers (disregard the ability to enter non-numbers). The app calculates the s ...

Guide to adding a line break following each set of 200 characters utilizing jQuery

I have a text input field where I need to enter some data. My requirement is to automatically add a line break after every 200 characters using JavaScript or jQuery. For example: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ...

Altering the text of dropdown items prior to the ASP.NET autopostback

Recently, I inherited a project from a client that is plagued with some irritating issues. One particular problem involves a dropdown menu that triggers an autopostback event upon selection change, inserting the selected text into a T-SQL query. The troubl ...

Utilizing Angular.js to extract data from a deeply nested array of objects in JSON

Hello, I am currently learning about Angular.js and working on developing a shopping cart. In this project, I need to display an image, name, and cost of each product for multiple tenants. Each tenant has an array called listOfBinaries which contains listO ...

My Express server is having trouble loading the Static JS

I'm feeling frustrated about this particular issue. The problem seems to be well-solved, and my code looks fine, but I can't figure out what's wrong . . . I have a JavaScript file connecting to my survey page, which I've added at the b ...

GWT integration for TinyMCE

I've been attempting to incorporate TinyMCE with GWT's RichTextBox, but so far I haven't had any luck. The issue seems to be that GWT turns the Rich text area into a #document, rather than a standard textarea in HTML. Does anyone know how to ...

Vue.js2 - Detection of Observer in Array

A question for beginners in vue.js. I am trying to display data using the CanvasJS Library that is received via websocket. Everything works fine with the data until I introduce vue components into the mix. Let me clarify: export default { data() { r ...

Tips for setting up Nginx with Node.js on a Windows operating system

I am looking to set up Nginx on my Windows machine in order to run two node applications. Can anyone provide guidance on how to accomplish this? I have attempted to download Nginx 1.6.3, but have had trouble finding instructions specifically for running i ...

Is JQueries Live functionality compatible with IE8?

Incorporating the JQuery fancy box, I have implemented a pop-up form with select fields that dynamically update a span element upon selection change. Although it works well thanks to fellow Stack Overflow users' help, it unfortunately does not functio ...

Decoding JavaScript content with Python

Currently, I am dissecting this specific portion of HTML <script type="text/javascript"> var spConfig = new Product.Config({"attributes":{"150":{"id":"150","code":"size_shoe","label":"Schuhgr\u00f6\u00dfe","options":[{"id":"494","label ...