I haven't been able to find anything like
$rootScope
for React Native and I want to share a couple variables between different Views.
I haven't been able to find anything like
$rootScope
for React Native and I want to share a couple variables between different Views.
For example, you can export class with static properties and then import there when need.
In main.js for example:
export class AppColors {
static colors = {main_color: "#FFEB3B", secondary_color: "#FFC107"}
}
In other file, where need to get this colors
import { AppColors } from './main.js';
class AnotherPage {
constructor() {
super();
console.log(AppColors.colors); // youla! You will see your main and secondary colors :)
}
}
Storing variables in the global scope is a bit of an anti-pattern in React. React is intended to be used with a one-way data flow, meaning data flows down from components to their children. This is achieved through the passing of props.
In order to share a value between multiple views, you would either need to store the data on a shared parent component and pass it down as a prop
OR store it in a separate entity that is responsible for data management. In ReactJS this is achieved through patterns like Flux, but I'm not sure about the options for react-native.
Step 1. create ConstantFile.js
File and put this code.
export class ConstantClass {
static webserviceName = 'http://172.104.180.157/epadwstest/';
static Email = 'emailid';
static Passoword = 'password';
}
Step 2. Access as like below. But before that, you need to import
your js file to particular class file something like that
import { ConstantClass } from './MyJS/ConstantFile.js';
ConstantClass.webserviceName
ConstantClass.Email
ConstantClass.Passoword
You can store those values in parent components state. Then pass methods changing those values via props or context / or like @Jakemmarsh suggested - use Flux/Redux approach.
OR, you can use AsyncStorage. Its useful for storing app data like tokens and such.