react native-tutorial

React Native Passing Value between Screen

One of the most helpful things when we have an application that has to communicate between the various displays is passing the value from one screen to another. This allows us to transfer data between various activities with ease. the function props.navigation.navigate(), which is used to switch between displays. We can easily pass the value and obtain it from other screens using the same way.

We’ll transfer an input from the first screen to the second screen in the example below.

To Make a React Native App

Learning more about how to create a React Native project can benefit you as you get started with React Native. To create our React Native app, we’ll utilise react-native init. If node is already installed on your computer, you may install the react-native-cli command line tool using npm. Go to the workspace, launch the terminal, and then

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependencies

To navigate between screens we need to add react-navigation and other supporting dependencies. To install the dependencies open the terminal and jump into your project

cd ProjectName

1. Install react-navigation

npm install @react-navigation/native --save

2. Other supporting libraries react-native-gesture-handler, react-native-reanimated, react-native-screens and react-native-safe-area-context and @react-native-community/masked-view

npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view --save

3. For the Stack Navigator install

npm install @react-navigation/stack --save

Note: When you use a navigator (such as stack navigator), you’ll need to follow the installation instructions of that navigator for any additional dependencies. If you’re getting an error “Unable to resolve module”, you need to install that module in your project.

You might get warnings related to peer dependencies after installation. They are usually caused by incorrect version ranges specified in some packages. You can safely ignore most warnings as long as your app builds.

CocoaPods Installation

Please use the following command to install CocoaPods

npx pod-install ios

To finalize the installation of react-native-gesture-handler, add the following at the top (make sure it’s at the top and there’s nothing else before it) of your entry files, such as index.js or App.js:

import 'react-native-gesture-handler';

Note: If you skip this step, your app may crash in production even if it works fine in development.

Code

Now open App.js in any code editor and replace the code with the following code

App.js

import 'react-native-gesture-handler';
import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack'; 
import FirstPage from './pages/FirstPage';
import SecondPage from './pages/SecondPage';
 
const Stack = createStackNavigator();
 
const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="FirstPage">
        <Stack.Screen
          name="FirstPage"
          component={FirstPage}
          options={{
            title: 'First Page', //Set Header Title
            headerStyle: {
              backgroundColor: '#f4511e', //Set Header color
            },
            headerTintColor: '#fff', //Set Header text color
            headerTitleStyle: {
              fontWeight: 'bold', //Set Header text style
            },
          }}
        />
        <Stack.Screen
          name="SecondPage"
          component={SecondPage}
          options={{
            title: 'Second Page', //Set Header Title
            headerStyle: {
              backgroundColor: '#f4511e', //Set Header color
            },
            headerTintColor: '#fff', //Set Header text color
            headerTitleStyle: {
              fontWeight: 'bold', //Set Header text style
            },
          }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
};
 
export default App;

Open pages/FirstPage.js in any code editor and replace the code with the following code

FirstPage.js

import React, {useState} from 'react';
import {
  SafeAreaView,
  StyleSheet,
  View,
  Text,
  TextInput,
  Button,
} from 'react-native';
 
const FirstPage = ({navigation}) => {
  const [userName, setUserName] = useState('AboutReact');
 
  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={styles.container}>
        <Text style={styles.heading}>
          React Native Pass Value From One Screen to Another
          Using React Navigation
        </Text>
        <Text style={styles.textStyle}>
          Please insert your name to pass it to second screen
        </Text>
        {/*Input to get the value from the user*/}
        <TextInput
          value={userName}
          onChangeText={(username) => setUserName(username)}
          placeholder={'Enter Any value'}
          style={styles.inputStyle}
        />
        {/* On click of the button we will send the data as a Json
          From here to the Second Screen using navigation */}
        <Button
          title="Go Next"
          //Button Title
          onPress={() =>
            navigation.navigate('SecondPage', {
              paramKey: userName,
            })
          }
        />
      </View>
    </SafeAreaView>
  );
};
 
export default FirstPage;
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    padding: 20,
  },
  heading: {
    fontSize: 25,
    textAlign: 'center',
    marginVertical: 10,
  },
  textStyle: {
    textAlign: 'center',
    fontSize: 16,
    marginVertical: 10,
  },
  inputStyle: {
    width: '80%',
    height: 44,
    padding: 10,
    marginVertical: 10,
    backgroundColor: '#DBDBD6',
  },
});

Open pages/SecondPage.js in any code editor and replace the code with the following code

SecondPage.js

import React from 'react';
import {SafeAreaView, StyleSheet, View, Text} from 'react-native';
 
const SecondPage = ({route}) => {
  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={styles.container}>
        <Text style={styles.heading}>
          React Native Pass Value From One Screen to Another
          Using React Navigation
        </Text>
        <Text style={styles.textStyle}>
          Values passed from First page: {route.params.paramKey}
        </Text>
      </View>
    </SafeAreaView>
  );
};
 
export default SecondPage;
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    padding: 20,
  },
  heading: {
    fontSize: 25,
    textAlign: 'center',
    marginVertical: 10,
  },
  textStyle: {
    textAlign: 'center',
    fontSize: 16,
    marginVertical: 10,
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

To run the project on an Android Virtual Device or on real debugging device

react-native run-android

or on the iOS Simulator by running (macOS only)

react-native run-ios

Output:

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published. Required fields are marked *