Global Scope Variables
We all know either we are developing any web or any mobile app, We always need Global Scope Variables. If you are not familiar with the global variable just think about the variables which can be accessed from any screen/activity after first initialization.
They can be used on any screen as local variables but the difference is their scope is global. In React Native we can make any variable Global Scope Variables by just putting global
as prefix.
Example of Global Scope Variables
If we have myvar
which is a local variable and accessible only from the same class. and if we have global.myvar
then it becomes global and can be accessed from any class of the application.
Here is an example to understand it. We have a global.MyVar
variable initialized in the first screen which can be accessed from First Screen as well as from the Second Screen.
To Make a React Native App
Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
This will make a project structure with an index file named App.js in your project directory.
We are going to use the react-navigation library to switch our screen so you need to install the same.
Installation of Dependencies
To switch between the screens we need to add react-navigation in our application. To install the dependencies open the terminal and jump into your project
cd ProjectName
Now run the following commands to install the dependencies
npm install @react-navigation/native --save
npm install @react-navigation/native-stack --save
npm install react-native-screens react-native-safe-area-context --save
react-native-screens
package requires one additional configuration step to properly work on Android devices. Edit MainActivity.java
file which is located in android/app/src/main/java/<your package name>/MainActivity.java
.
Add the following code to the body of MainActivity
class:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(null);
}
and make sure to add the following import statement at the top of this file below your package statement:
import android.os.Bundle;
This change is required to avoid crashes related to View state being not persisted consistently across Activity restarts.
These commands will copy all the dependencies into your node_module directory.
CocoaPods Installation
Please use the following command to install CocoaPods
npx pod-install
Project File Structure
To start with this Example you need to create a directory named pages in your project and create two files FirstPage.js and SecondPage.js
Code
Now Open App.js in any code editor and replace the code with the following code.
App.js
// React Native Global Scope Variables
// https://aboutreact.com/react-native-global-scope-variables/
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import FirstPage from './pages/FirstPage';
import SecondPage from './pages/SecondPage';
const Stack = createNativeStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator
initialRouteName="FirstPage"
screenOptions = {{
headerStyle: {backgroundColor: '#f4511e'},
headerTintColor: '#fff',
}}
>
<Stack.Screen
name="FirstPage"
component={FirstPage}
options={{title: 'First Page'}}
/>
<Stack.Screen
name="SecondPage"
component={SecondPage}
options={{title: 'Second Page'}}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
Open pages/FirstPage.js in any code editor and replace the code with the following code.
FirstPage.js
// React Native Global Scope Variables
// https://aboutreact.com/react-native-global-scope-variables/
import React from 'react';
import {
Button,
View,
Text,
SafeAreaView
} from 'react-native';
const FirstPage = ({navigation}) => {
global.MyVar = 'https://aboutreact.com';
return (
<SafeAreaView style={{flex: 1}}>
<View style={{flex: 1, padding: 16}}>
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}}>
<Text
style={{
fontSize: 25,
textAlign: 'center',
marginBottom: 16,
}}>
This is the First Page of the App
</Text>
<Text
style={{
fontSize: 18,
textAlign: 'center',
marginBottom: 16,
color: 'red',
}}>
Value of Global Variable is: {global.MyVar}
</Text>
<Button
onPress={
() => navigation.navigate('SecondPage')
}
title="Go to Second Page"
/>
</View>
<Text
style={{
fontSize: 18,
textAlign: 'center',
color: 'grey'
}}>
React Native Global Scope Variables
</Text>
<Text
style={{
fontSize: 16,
textAlign: 'center',
color: 'grey'
}}>
www.aboutreact.com
</Text>
</View>
</SafeAreaView>
);
};
export default FirstPage;
Open pages/SecondPage.js in any code editor and the Replace the code with the following code.
SecondPage.js
// React Native Global Scope Variables
// https://aboutreact.com/react-native-global-scope-variables/
import React from 'react';
import {
View,
Text,
SafeAreaView
} from 'react-native';
const SecondPage = () => {
return (
<SafeAreaView style={{flex: 1}}>
<View style={{flex: 1, padding: 16}}>
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}}>
<Text
style={{
fontSize: 25,
textAlign: 'center',
marginBottom: 16,
}}>
This is Second Page of the App
</Text>
<Text
style={{
fontSize: 18,
textAlign: 'center',
marginBottom: 16,
color: 'red',
}}>
Value of Global Variable is: {global.MyVar}
</Text>
</View>
<Text
style={{
fontSize: 18,
textAlign: 'center',
color: 'grey'
}}>
React Native Global Scope Variables
</Text>
<Text
style={{
fontSize: 16,
textAlign: 'center',
color: 'grey'
}}>
www.aboutreact.com
</Text>
</View>
</SafeAreaView>
);
};
export default SecondPage;
To Run the React Native App
Open the terminal again and jump into your project using.
cd ProjectName
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Output Screenshot
This is how you can make a Global Scope Variables. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!
Hope you liked it. 🙂
Your program always have missing piece.
In the App.js, you do not have render().
Sharing your knowledge and suggestion is a good thing but instead of reading the code can you please run the code and try to understand the code. App.js is my index file which is used for the navigation setup of my two screens and have no component to return other than the createStackNavigator. If you have any other way can you please share it with others also?
Thanx for your comment. 🙂
The global variable could be change his value?
Yes, we can change the value of the global variable.
Awesome thanks. I am not inclined to learn nor adopt state management software like redux or flux e.g. But I want to learn that can we change global variable as we wish or are they constant values that should not be changed.
We can change the global variable from anywhere and anytime within the application. I also want to add that we can not compare the global variable with the Redux or Flux as they can be used for managing the state from a single location and global variables just stores value and do not affect the state.
Thank you for the tutorial. I really appreciate this! Keep on being awesome :>
global, how did I not know about this
You can access it from anywhere
Thank you this was helpful