Create Global Scope Variables in React Native used between Activities

There are by default two types of variables in react native, Local Variable and Global Variable. Local variables is used within defined scope and Global variables can be use at any place within any activity and can be changeable from any where. You can read about Local Variables from Here. React Native did support Global Scope Variables which can be used between multiple activities. So in this tutorial we would going to Create Global Scope Variables in React Native used it between multiple Activities.

Syntax of declaring Global Variable (Prototype): We have to use inbuilt keyword global to create global variables. See the below code for more details.

What we are doing in this project:

We are creating react native app with 2 activities. Now we would declare the Global Variable in first MainActivity inside the constructor(). Now we would use this variable in second activity and show it inside Text component.

Contents in this project Create Global Scope Variables in React Native Android iOS App:

1. Import react-navigation library in your project to add activity structure because we cannot use multiple activities in our project without adding react navigation library. Open your project’s folder in CMD and execute
npm install save reactnavigation command.


2. Import StyleSheet, View, Text and Button component in your project.

3. Import StackNavigator module from react navigation library.

4. Create first class in your App.js file named as MainActivity. We would declare the Global Variable inside this class in constructor() function.

constructor() : We would create Global variable in constructor().

navigationOptions : Used to set Title of activity shows inside action title bar.

navigate2SecondActivity() : This function would navigate us to second activity.

5. Create another class named as SecondActivity. This is our next activity class, We would simply show the Global Variable in Text component.

6. Create StackNavigator() function after class. This function is inbuilt and we have to use this function to call activities.

7. Create Style.

8. Complete source code for App.js File :

Screenshots in Android device:

Create Global Scope VariablesScreenshots in iOS device: